简体   繁体   中英

Tic Tac Toe game in c++, issue with play again function

I'm a very beginner and I have an issue with this askPlayAgain function, made for a Tic Tac Toe game. When I finish the first game, the function works. It asks me if I want to play again or not. But after the second game ends, the program ends, telling me "player x won", without asking the yes or no question. Can you help me with this issue?

I will insert only the specific part of this project, because the site doesn't allow me to insert it all. If necessary, I will insert other parts of the project.

void askPlayAgain(string firstPlayer, string secondPlayer)
{

    char option;
    do {
        cout << "Play again? Y for yes, N for no" << endl;
        cin >> option;
        break;
    } while (option != 'Y' || option != 'y' || option != 'N' || option != 'n');

    if (option == 'Y' || option == 'y') {
        initializeTable();
        startGame(firstPlayer, secondPlayer);
    }
    else {
        exit(0);
    }
}

Let's think about your while condition--even just those for yes:

while (option != 'Y' || option != 'y')

In what case can this be false? With an OR, that'll only happen if both conditions are false. However, it's not possible for a character to both be 'Y' AND be 'y'.

Instead, you want AND's here:

while (option != 'Y' && option != 'y' && option != 'N' && option != 'n');

Or even cleaner could be:

std::string good_inputs = "YyNn";
do {
    // ...
} while (good_inputs.find(option) == std::string::npos);

However, none of that ever gets run ! You have a break in your while loop, so the condition is never checked. I'm not sure what your thought was there, but that should be removed.

You placed break statement after getting input(option) from user so what is the purpose of several conditions in while.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop ...

 do {
        cout << "Play again? Y for yes, N for no" << endl;
        cin >> option;
        break; 
    } while (option != 'Y' || option != 'y' || option != 'N' || option != 'n');


My suggested code:

{

char option;

        cout << "Play again? Y for yes, N for no" << endl;
        cin >> option;

    while(option != 'Y' && option != y && 'y' && option != 'N' && option != 'n')
{

cout << "invalid input enter again" << endl;
cin >> option;
// this loop run until user give right input
}
    if (option == 'Y' || option == 'y') {
        initializeTable();
        startGame(firstPlayer, secondPlayer);
    }
    else if(option == 'N' || option == 'n'){
        exit(0);
    }

}```

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