Using getline() in C++

MGE picture MGE · Sep 13, 2013 · Viewed 242.5k times · Source

I have a problem using getline method to get a message that user types, I'm using something like:

string messageVar;
cout << "Type your message: ";
getline(cin, messageVar);

However, it's not stopping to get the output value, what's wrong with this?

Answer

Natan Streppel picture Natan Streppel · Sep 13, 2013

If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.