0

I'm at a loss of what to do here. So I have this simple while loop meant to allow a user to re-input a number if they accidentally give an incorrect input. The issue is, if you input "2" it loops back again. I can't, for the life of me figure it out.

void Player::playerPick()
{
    int selection = 0;
    while (selection != (1 || 2))
    {
        cout << "Player 1 or Player 2 (Type [1] or [2])";
        cin >> selection;
    }
}
5
  • while (selection != 1 && selection != 2) Commented May 12, 2017 at 18:06
  • 2
    (1 || 2) is true. You wrote while(selection != true). Many compilers issue a warning. Commented May 12, 2017 at 18:06
  • Might be difficult to find the duplicate, but this has been asked before. Commented May 12, 2017 at 18:20
  • @crashmstr: The usual mistake is (selection!=1 || 2). That's not a duplicate because it means ((selection!=1) || 2) Commented May 12, 2017 at 21:44
  • @MSalters I would argue that even though the result here is different due to the parentheses, the underlying misunderstanding of comparison operators is still the same (this person just tried ()), and that the answer is also fundamentally the same. Commented May 13, 2017 at 1:30

1 Answer 1

4

You wrote:

while (selection != (1 || 2))

This is "while selection is not one or two".

The actual correct English is "while selection is neither one nor two", and that's true in C++ also:

while (!(selection == 1 || selection == 2))

Or, simpler, "while selection is not one, and selection is not two":

while (selection != 1 && selection != 2)

The expression 1 || 2 evaluates to true, so you wrote while (selection != true), which is the case for any non-zero value of selection.

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

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.