C++ correcting invalid (string) user input in tictactoe when integer is expected


In the tictactoe challenge I ask the user to insert a number corresponding with one of the nine places. I have a question about what happens when a user inserts a string instead of a number. Here is all the code on github

In the code below the program keeps on repeating the cout and doesn’t wait for new input from the user. Also if only the cin statement would be in the while block it wouldn’t accept a new input.

int get_choice(std::vector<char> grid) {
    int choice = 0;
    std::cin >> choice;
    while (choice > 9 || choice < 1 || grid[choice-1] == 'O' || grid[choice-1] == 'X') {
        std::cout << "\n\nInvalid choice, please, choose again.\n";
        std::cin >> choice;
    return choice;

I’m really curious as to why this happens!

Long story short(and oversimplified) - when the string came in where an int was expected your buffer entered into a fail state. Now your buffer is ‘poisoned’ with bad input.
You need to get rid of the bad input in your buffer, and tell your buffer that it is no longer in a fail state.

while(std::cin.fail() || choice > 9 || choice <  1)
        std::cin >> choice;

std::cin.fail() simply tells you whether or not the buffer is in a fail state
if it is, or the input isn’t what we wanted then we clear the fail state, and ignore either up to 1000 characters or a newline in the buffer ( up to you what to put here, it’s unlikely your user put over 1000 characters and very likely their input ended with a newline)

1 Like

Thanks for your reaction, the short and simplified version is very unterstandable and gives me a good start of this concept :smiley: !
This is new to me, very interesting!

good luck with the dragons!