我想在读文件时跳过空行。
我试过if(buffer ==“\n”)和if(buffer.empty()),但都不起作用。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file_pointer;
file_pointer.open("rules.txt", ios::in);
if(!file_pointer.is_open())
{
cout << "failed to read rule file." << endl;
return 0;
}
string buffer;
while(getline(file_pointer, buffer))
{
if(buffer.empty())
{
continue;
}
if(buffer == "\n")
{
continue;
}
cout << buffer << endl;
}
file_pointer.close();
return 0;
}
3条答案
按热度按时间7dl7o3gd1#
问题是“空白”行不一定是“空的”。
几个音符。
std::
,用using namespace std
导入所有的东西几乎总是一个坏主意。main()
返回1
来通知程序失败。main()
返回0
来表示程序成功。std::any_of()
和lambdas很可能是你还没有研究过的东西,is_blank()
有各种各样的写法:或者:
等等。
检查换行符不起作用的原因是
getline()
从输入流中删除了换行符,但没有将其存储在目标字符串中(不像fgets()
,它 * 确实 * 存储了换行符,以便您知道您从用户那里得到了一整行文本)。总的来说,你看起来有一个良好的开端。我真的建议你让自己熟悉一个好的参考,并查找你希望使用的功能。即使是现在,经过30多年的这样做,我仍然查找他们当我使用他们。
找到好东西的一种方法是在Google上输入函数的名称:“cppreference.comgetline”将带您访问ur-reference站点。
qc6wkl3g2#
在C++中阅读文件时,可以跳过空行,方法是使用getline()函数并检查结果字符串的长度。下面是一个如何做到这一点的示例:
你也可以使用std::stringstream类来跳过空行,下面是一个例子:
w1e3prcc3#
**(1)**这里有一个解决方案,它将
ws
操作器与getline
函数结合使用,以便在从流中阅读输入行时忽略前导空格。ws
是一个跳过空格字符的操作器(demo)。请注意,即使该行不为空(
" abc "
变为"abc "
),前导空格也会被删除。**(2)**如果这是一个问题,您可以用途: