我该如何检测一行是否为空?
我有以下代码:
1
2
3
4
5
我正在使用 istream r 进行阅读:
int n;
r >> n
我想知道何时到达4和5之间的空格。
我尝试以字符方式读取并使用.peek()来检测\n,但这会检测到1后面的\n。如果我没错,上述输入的翻译是: 1\n2\n3\n4\n\n5\n...由于我将操纵整数,所以我宁愿将它们作为整数读取,而不是使用getline然后转换为整数...
它可能看起来像这样:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream is("1\n2\n3\n4\n\n5\n");
string s;
while (getline(is, s))
{
if (s.empty())
{
cout << "Empty line." << endl;
}
else
{
istringstream tmp(s);
int n;
tmp >> n;
cout << n << ' ';
}
}
cout << "Done." << endl;
return 0;
}
输出:
1 2 3 4 Empty line.
5 Done.
希望这可以帮到你。
std::getline
将每一行读取为一个string
。然后,您可以基于该字符串创建临时的istringstream
并从中读取。我已经编辑了我的答案。 - LihOwhile (is.good())
几乎总是错误的,而且肯定是错误的。请使用 while(getline(is, s))
。 - Martin York#include <iostream>
using namespace std;
int main()
{
int x;
while (!cin.eof())
{
cin >> x;
cout << "Number: " << x << endl;
char c1 = cin.get();
char c2 = cin.peek();
if (c2 == '\n')
{
cout << "There is a line" << endl;
}
}
}
但要注意,这种方法并不可移植。当你使用的系统具有不同于 '\n' 的行尾字符时,会出现问题。考虑读取整行,然后从中提取数据。
std::getline
将每行读入一个std::string
,检查字符串长度。使用例如std::istringstream
从输入的每一行中读取单个项目。这也有助于处理错误输入。祝好运! - Cheers and hth. - Alf