简体   繁体   中英

tic-tac-toe while and ||

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.

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') {

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');

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

while ( (player == 'x' || player == 'o') == false )
    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;
    };

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