In this case, I think using
std::cin >> value
instead of
getline(std::cin, value);
is a reasonable solution.
When the string to be entered consists of multiple words, getline is appropriate, but here the input is a single word and cin >> value is just fine.
There is a difference in the way these functions behave.
cin >> value
will read from the input stream only up to the first whitespace character. Any unused characters will remain in the input buffer and may be accepted by the next cin command. There will usually be a newline character '\n' left in the buffer afterwards.
On the other hand, getline reads all characters up to the first newline character, and then reads and discards the newline itself.
When this sequence is executed:
1 2
|
cin >> value1;
getline(cin, value2);
| |
the first line leaves the '\n' in the buffer, the second line reads an empty string and then discards the newline.
A solution is to use
cin.ignore()
or
cin.ignore(1000,'\n')
to discard unwanted characters from the input buffer. The first ignores a single character, the second ignores up to 1000 characters, or until the newline is found.
1 2 3
|
cin >> value1;
cin.ignore();
getline(cin, value2);
| |