Problem of using cin twice.

Posted by gc on Stack Overflow See other posts from Stack Overflow or by gc
Published on 2010-03-26T17:30:11Z Indexed on 2010/03/26 17:33 UTC
Read the original article Hit count: 251

Filed under:
|

Here is the code:

string str;
cin>>str;
cout<<"first input:"<<str<<endl;
getline(cin, str);
cout<<"line input:"<<str<<endl;

The result is that getline never pauses for user input, therefore the second output is always empty.

After spending some time on it, I realized after the first call "cin>>str", it seems '\n' is still stored in cin (using cin.peek() to check), which ends getline immediately. The solution will be adding one more line between the first usage and the second one: cin.ignore(numeric_limits::max(), '\n');

However, I still don't understand, why is '\n' left there after the first call? What does istream& operator>> really do?

© Stack Overflow or respective owner

Related posts about c++

Related posts about cin