To allow a multiple words user input I use getline
and I flush the stream according to this answer with this code :
while(!everyoneAnswered()){
string name;
std::cout << "enter your name : ";
if (getline(std::cin, name)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // flush stream
std::cout << "enter your age : ";
int age;
std::cin >> age;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// stuff
}
}
The problem is that now the user has to hit enter two times for the input to get accepted. I guess it's because getline
consumes the first \n
.
How can I avoid this, so that the user only hit enter once for the input to validate?
Here is an example of the result without the flush:
enter your name : foo
enter your age : 42
enter your name : enter your age : 69
--crashing because second name is empty--
Here is an example of the result with the flush :
enter your name : foo
enter your age : 42
enter your name : bar
enter your age : 69
Finally the flush without \n
delimiter hangs on the first try waiting for MAX_INT
characters entered.
I use gcc
version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04
).