getline(cin, aString) receiving input without another enter

Shane Hsu picture Shane Hsu · Feb 23, 2012 · Viewed 16.6k times · Source

My code looks like this,

string aString;
cin >> aString;
cout << "This is what cin gets:" << aString << endl;
getline(cin, aString);
cout << "This is what getline(cin, <string>) gets:" << aString << endl;

Each time I ran it, I give inputs like, "12", I get "12" and "".

I am wondering why getline would received without user input.

I can understand when I enter something like "12 24", cin will get "12", and getline should get the rest. (Also, if one could answer, the space in between is treated as an end for cin, so why is it passed on to getline?)

Just starting out on string on C++ so please don't make it too hard. Thanks you.

Answer

templatetypedef picture templatetypedef · Feb 23, 2012

When you mix standard stream extraction with getline, you will sometimes have getline return the empty string. The reason for this is that if you read input with >>, the newline character entered by the user to signal that they're done is not removed from the input stream. Consequently, when you call getline, the function will read the leftover newline character and hand back the empty string.

To fix this, either consistently use getline for your input, or use the ws stream manipulator to extract extra white space after a read:

cin >> value >> ws;

This will eat up the newline, fixing the problem.

Hope this helps!