1

hi im 17 and trying to teach myself c++. For one of my first projects I am trying to write a tic-tac-toe game and play vs an AI. So the code im having trouble with is this

main() {

    char player, computer;

    while (player != 'x' || player != 'o' )
    {
        cout << "do you want to be x or o?";
        cin >> player;
    };

    if (player == 'x' ) computer == 'o';
    else computer == 'x';

    cout << "player is: " << player << endl <<  "computer is: " << computer ;
    cout << computer;
};

I get the message " do you want to be x or o?", but then I enter x or o and it keeps repeating the same question. I think it has to do with the while loop. Any help is appreciated.

Patrick Kennedy
  • 177
  • 2
  • 2
  • 11

5 Answers5

7
char player, computer;

while (player != 'x' || player != 'o' ) {

First of all, player isn't initialized to anything, so it contains random garbage. You shouldn't be reading from it. At least initialize it to some known value.

Second, your condition will always be true. Suppose that player is 'x'. That satisfies the condition player != 'o'.

You probably mean:

while (player != 'x' && player != 'o') {
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • ahh thanks, that clarifies it for me now, but what should i initialize player to and how would i do that? – Patrick Kennedy Feb 21 '12 at 05:09
  • In your case, you could just initialize it something that isn't `'x`' nor `'o'` (for example: `char player = 'a';`). But using a `do-while` loop like StilesCrisis mentions would be better so that you check the `player` value only after you've written to it. – jamesdlin Feb 21 '12 at 05:13
5

Your loop end condition is wrong, and you shouldn't check until you've asked once.

do {
    cout << "do you want to be x or o?";
    cin >> player;
} while (player != 'x' && player != 'o');
StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
1

Your problem is the conditional. What I think you mean is while (player != 'x' && player != 'o'), i.e. when player is neither x nor o.

Luke
  • 7,110
  • 6
  • 45
  • 74
0
while ( (player == 'x' || player == 'o') == false )
Farzher
  • 13,934
  • 21
  • 69
  • 100
0
    char player = ' '; // always init variables
    while (player != 'x' && player != 'o' ) //exit if false, when player == x or == o
    {
        cout << "do you want to be x or o?";
        cin >> player;
    };
Dmitriy Kachko
  • 2,804
  • 1
  • 19
  • 21