문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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 problem is the conditional. What I think you mean is while (player != 'x' && player != 'o'), i.e. 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;
    };
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top