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

前端 未结 2 1979
时光取名叫无心
时光取名叫无心 2020-12-29 10:15

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
         


        
2条回答
  •  心在旅途
    2020-12-29 11:01

    It could look like this:

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

提交回复
热议问题