2

The following code contains a logical error every time i run it and enter 1 or 0 the code in the while loop is still executed. can someone tell me why?

bool getmove()
{
    bool move;
    cout << "Would you like to make the first move?(1 for yes 0 for no)\n";
    cin >> move;
    while(move != 1 || move != 0 || !cin.good())
    {
        if(!cin.good())
        {
            cout << "ERROR please try again\n";
            cin.clear();
            cin.ignore(80,'\n');
            cin >> move;
        }
        else
        {
            cout << "Invalid input please try again\n";
            cin >> move;
        }
    }
    return move;
}

2 Answers 2

1

Look at this line:

while(move != 1 || move != 0 || !cin.good())

It will always be the case that move != 1 || move != 0 (because it can't be both).

Furthermore, you'll avoid some trouble by reading in something like a string and testing that, rather than relying on casting.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much i dont know how i missed that. i could do: while((move != 1 && move !=0 ) || !cin.good)
1

If you're trying to write a function which can validate the input of a boolean value, your code can be simplified to:

bool getmove()
{
    bool move;
    cout << "Would you like to make the first move?(1 for yes 0 for no)\n";
    while (!(cin >> move))
    {
        cout << "Invalid input please try again\n";
        cin.clear();
        cin.ignore(80, '\n');
    }
    return move;
}

It is important to realize that while (!(cin >> move)) will repeat the loop until a valid boolean value can be read from the console and written into move.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.