C++ 从C++中的istream对象读取时如何检测空行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9235296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect empty lines while reading from istream object in C++?
提问by bb2
How can I detect if a line is empty?
如何检测一行是否为空?
I have:
我有:
1
2
3
4
5
I'm reading this with istream r so:
我正在使用 istream r 阅读此内容,因此:
int n;
r >> n
I want to know when I reach the space between 4 and 5. I tried reading as char and using .peek() to detect \n but this detects the \n that goes after number 1 . The translation of the above input is: 1\n2\n3\n4\n\n5\n if I'm correct...
我想知道什么时候到达 4 和 5 之间的空间。我尝试读取为 char 并使用 .peek() 来检测 \n 但这会检测到数字 1 之后的 \n 。上述输入的翻译是: 1\n2\n3\n4\n\n5\n 如果我是对的...
Since I'm going to manipulate the ints I rather read them as ints than using getline and then converting to int...
由于我要操作整数,我宁愿将它们作为整数读取,而不是使用 getline 然后转换为整数...
回答by LihO
It could look like this:
它可能看起来像这样:
#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;
}
output:
输出:
1 2 3 4 Empty line.
5 Done.
Hope this helps.
希望这可以帮助。
回答by gumik
If you really don't want using getline, this code works.
如果您真的不想使用 getline,则此代码有效。
#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;
}
}
}
But be aware that this is not portable. When you using system that has different end lines characters than '\n' then would be problem. Consider reading whole lines and then extract data from it.
但请注意,这不是便携式的。当您使用具有与 '\n' 不同的结束行字符的系统时,就会出现问题。考虑读取整行,然后从中提取数据。