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

前端 未结 2 1980
时光取名叫无心
时光取名叫无心 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 10:58

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

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

提交回复
热议问题