如何在C++中从istream对象读取时检测空行?

bb2*_*bb2 11 c++ string input stream istream

如何检测线是否为空?

我有:

1
2
3
4

5
Run Code Online (Sandbox Code Playgroud)

我正在用istream r读这个:

int n;
r >> n
Run Code Online (Sandbox Code Playgroud)

我想知道当我到达4到5之间的空间时.我尝试读取为char并使用.peek()来检测\n但是这会检测到数字1之后的\n.以上输入的翻译是:1 \n2 \n3 \n4 \n \n5 \n如果我是正确的...

因为我要操作整数,所以我宁愿把它们作为整数读取而不是使用getline然后转换为int ...

Lih*_*ihO 19

它可能看起来像这样:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 2 3 4 Empty line.
5 Done.
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • @ bb2:在这种情况下,我肯定会使用`std :: getline`来读取每一行作为`string`.然后你可以根据该字符串创建临时的`istringstream`并从中读取.我编辑了我的答案. (2认同)
  • **失败**:您报告了一个额外的空行。这样做`while (is.good())` 实际上总是错误的,而且在这里绝对是错误的。使用`while(getline(is, s))` (2认同)

gum*_*mik 5

如果你真的不想使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但请注意,这不是便携式的.当您使用具有与'\n'不同的结束行字符的系统时,那将是问题.考虑读取整行,然后从中提取数据.

  • 说这是不可移植的是不正确的。系统的换行符与“\n”相互转换。 (2认同)