Search code examples
c++error-handlingwhile-loopistream

Whenever i use while(cin>>(var)) in my code, the istream gets stuck in error state


The code i am trying to run is given below. Here in line 9 I am trying to take multiple inputs using the while(cin>>n) method. The input I gave is like :

2 4 5 6 45 357 3 (ctrl+z)(ctrl+z)

to indicate EOF in windows.

Then, even thought the numbers get added into the vector v1, the istream is stuck into error state cause the output I get this :

error2 4 5 6 45 357 3.

And I can also confirm that istream is stuck in error state cause if I use another cin statement after this, it gets ignored by the compiler until I clear the stream by cin.clear() function.

Can anybody please tell me why does this happen and how can I prevent the stream getting into error state. or is it something normal and I must use cin.clear() after every while(cin>>(var)) statement?

#include <iostream>
#include <vector> 

using std:: cin; using std:: cout; using std::endl;using std::vector;
int main(){
vector<int> v1;
int n;
cout<< "enter the list of numbers";
while(cin>>n){
    v1.push_back(n);
}
if((cin>>n).fail()){cout<<"error";}
for (auto i: v1){
    cout<< i<<" ";
}

https://godbolt.org/z/c54dGdWcq


Solution

  • the statement cin>>n return the cin object itself, put it inside while does something like

    while(true){
       cin >> n;
       if(cin){ // equals to if(!cin.fail())
          // ... body of while
       }
       else break;
    }
    

    so yes, after you leave the loop, cin is in fail state, thus any subsequence operator >> would not success until you call clear.


    relevant: https://en.cppreference.com/w/cpp/io/ios_base/iostate