Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem of using cin twice

Tags:

c++

cin

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?

like image 601
gc . Avatar asked Mar 26 '10 17:03

gc .


2 Answers

The \n is left in the input stream as per the way operator>> is defined for std::string. The std::string is filled with characters from the input stream until a whitespace character is found (in this case \n), at which point the filling stops and the whitespace is now the next character in the input stream.

You can also remove the \n by calling cin.get() immediately after cin>>str. There are many, many different ways of skinning this particular I/O cat, however. (Perhaps a good question in and of itself?)

like image 95
fbrereto Avatar answered Sep 18 '22 00:09

fbrereto


By default, the stream insertion operator reads until it sees whitespace. Your first call isn't returning until it sees a space, tab, newline, etc. Then the next character needs to be consumed so that you can get to the next one.

like image 28
jwismar Avatar answered Sep 18 '22 00:09

jwismar