c++if-statementoperators

C++ The if statement is still true even when only one condition is met


I am creating a tic tac toe program in c++ and am almost finished with it, the issue I'm having is when the game needs to end in a tie. I created an if-statement to check when specific combinations are selected and it finds it true even when only one condition is met.

Here is the code...

//takes the users selections and sees if all spots are filled in without a match.
if((b1== "O" || "X") && (b2 == "O" || "X") && (b3 == "O" || "X")){
        cout << "The game ended in a tie.";
      // Flip = 3 ends the game in a tie.
        flip = 3;
    }


ex... the game ends in a tie when i change `b1` to and `"O"` or an `"X"` even though `b2` and `b3` are still empty.

Solution

  • The condition:

    b1== "O" || "X"
    

    evaluates as:

    (b1=="O") || "X"
    

    which is always true. You probably want:

    (b1=="O" || b1=="X")