0

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).

Silver Fox
  • 696
  • 4
  • 17
Nonoreve
  • 71
  • 2
  • 9
  • 1
    Does this answer your question: https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – jabaa Apr 30 '21 at 09:13

2 Answers2

1

The problem are these two lines:

if (getline(std::cin, name)) {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

The getline call includes the newline, so your ignore call will read the next line of input.

You need the ignore call after reading the age (with >>), but not after getline.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
-1

The solution was to also use getline() to read the age and parse it to an int. I don't know why mixing getline() and operator>> produces this behavior, though.

Nonoreve
  • 71
  • 2
  • 9
  • That's not the solution. That's a workaround. [Here](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) is the solution. _"What you'll have to do is discard the new line yourself before `std::getline()` runs (but do it after the formatted extraction)"_ You have to discard it after the formatted read, not after the unformatted read. – jabaa Apr 30 '21 at 09:19
  • Thanks, the other answer resolved the problem but your link gives a good explanation – Nonoreve Apr 30 '21 at 09:29