简体   繁体   中英

While loop carries on forever (C++)

I'm still quite new to c++ and just experimenting with the language.

I have recently created a 'tictactoe' game.

I have created this simple looking function to get the users board position (from 1 to 9). It seems to work fine but I found a weird bug so to call it;

Whenever I enter a 12 digit number or higher the loop just carries on forever printing 'Invalid position!' and on to the next line 'Choose your position 1-9: '.

I am using visual studio to write code. Is it something with the code or is it perfectly fine? I'm eager to find out to learn from it.

Here's the function:

int getUserPosition()
{
    int position;
    while (true)
    {
        cout << " Choose your position 1-9: " << endl;
        cin >> position;
        if (position < 1 or position > 9)
        {
            cout << "Invalid position!" << endl;
        }
        else if (board[position - 1] == 'X')
        {
            cout << "This position has been taken!" << endl;
        }
        else
        {
            return position;
            break;
        }
    }
}

I finally understand the actual behavior here. This is not invoking undefined behavior but rather defined behavior you don't want.

cin >> position;

This tried to read your 12 digit number, which didn't fit into an int, so the read failed. Because it failed on a format error, the 12 digit number remained in the buffer, so the next pass around the loop tried to read it again.

Always use cin::getline() when you intend to read keyboard input. The error/cleanup logic in cin is not designed to resync keyboard input, but rather to resync input piped from a generator that can't read your error messages. In the future, when you try to use cin with a pipe, the best solution is to check cin::fail() and bail the program if it ever gets set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM