std::cin >> age;
std::getline(std::cin, name);
Let's say the user enters the integer 5. This is what the input stream will look like:
5\n
...
Note that the above could vary. The user could enter an integer and subsequently a space character. Both are equally valid situations.
That is, the user enters the value and hits return to submit. operator >>
is formatted so that the integer will be consumed, but once it finds a new line or whitespace extraction will cease. After the input operation, the new line should still be in the stream.
\n
...
Now, let's see the content for name
:
\n
"Bruce Wayne"\n
When getline
executes, once it finds a new line in the stream it will stop searching for new input. The new line from the previous extraction was still in the stream, so the input was stopped immediately. Nothing was extracted!
Fortunately, we can use the ignore
method to discard the new line from the stream:
std::cin >> age;
std::cin.ignore(); // ignore the next character
std::getline(std::cin, age);
By default, std::cin.ignore
will discard the next character from the stream when given 0 arguments.
Here is a live example.