How to detect empty lines while reading from istream object in C++?

拟墨画扇 提交于 2019-12-30 02:09:07

问题


How can I detect if a line is empty?

I have:

1
2
3
4

5

I'm reading this with istream r so:

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...

Since I'm going to manipulate the ints I rather read them as ints than using getline and then converting to int...


回答1:


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.




回答2:


If you really don't want using getline, this code works.

#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.



来源:https://stackoverflow.com/questions/9235296/how-to-detect-empty-lines-while-reading-from-istream-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!