Problem with execiuting "getline" in "for loop"

Hello!
I wrote a small mathematics quiz. The function i have problem with should let the user enter the amount and names of players.
Problem appears when program enter the "for loop". Namely, "for loop" executes one time omitting the "getline" statement and then works correctly. Maybe it's trivial problem but i really can't find the reason of that issue. My OS is Windows and I'm using Code::Blocks IDE with GNU GCC compiler.

1
2
3
4
5
6
7
8
9
10
11
  int player_amount = 0;
        
        std::cout << "Enter amount of players: ";
        std::cin >> player_amount;
        string names[player_amount];

        for(int i = 0; i<player_amount; i++)
        {
            std::cout << "Name of player " << i + 1 << ": ";
            std::getline(std::cin,names[i]);
        }
On line 4, when you input the number of players, you press enter after the number. The number is read into player amount, but the newline is left behind. Then when you reach the first call to std::getline(), it reads that lone newline as you having pressed enter without any text in front of it, resulting in an empty string being read it.

You can use something like cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') after line 4 to ignore all input up to and including the newline so when you reach std::getline() this problem does not occur.
Thank u so much! That total solves my problem. I have not used console input to much form a long time :).
Last edited on
An easier way to flush the input buffer is to use the function
cin.sync();

It does the same thing but is shorter to type.
it is implementation-defined whether this function does anything with library-supplied streams. ...
sync() may empty the get area, or it may refill it, or it may do nothing.

... Visual Studio, where this operation discards the unprocessed input when called with a standard input stream.

http://en.cppreference.com/w/cpp/io/basic_istream/sync
Topic archived. No new replies allowed.