Do-While loop executing again at false condition

Briefing: I have put a check of users valid input if he wants to play again or not. On selecting Y, the game restarts. On selecting N the game ends. But on selecting W (any other option) the game asks again for valid selection from Y or N. But this time if user selects N the game restarts. Where as the game should have ended.
Bug regeneration steps:

  1. Start the Game
  2. Enter abcd and press enter (do this 5 times in total)
  3. Enter W press enter (Game will ask again for valid input from Y or N)
  4. Enter N [bug: Logical error. The game should have ended but rather it starts again.]

Code snippet:
bool AskToPlayAgain(); //Function prototype

//Entry point
int main()
{
do {
PrintIntro();
PlayGame();
} while (AskToPlayAgain()); //AskToPlayAgain() returning true where it should return false as per the steps
return 0;
}

bool AskToPlayAgain() //Method definition
{
std::string playAgain = “”;
std::cout << "Do you want to play again? [Y/N]: ";
std::getline(std::cin,playAgain);
if (playAgain[0] == ‘y’ || playAgain[0] == ‘Y’)
{
return true;
}
else if (playAgain[0] == ‘n’ || playAgain[0] == ‘N’)
{
return false;
}
else
{
std::cout << “\nWrong input. Please enter again\n.”;
AskToPlayAgain();
}
}

Project Link:
BullCowGame.zip (241.6 KB)

Please let me know why is it happening?

Think about what’s happening when you call AskToPlayAgain in the else statement, what’s going to happen with the returned value.

Is it related to stack? Its a recursive function so, while popping, does it pops the return values backwords?

Does this illustrate the issue?

main
|-AskToPlayAgain()
 |- AskToPlayAgain() // --return true to caller ^
else
{
    std::cout << “\nWrong input. Please enter again\n.”;
    true;
}

If you can’t figure it out:

else
{
    std::cout << “\nWrong input. Please enter again\n.”;
    return AskToPlayAgain();
}

main
|-AskToPlayAgain()
|- AskToPlayAgain() // --return true to caller ^

This is the issue that it returns true to the caller, which is a condition for do-while iteration. Hence it iterates again. I tried debugging. In watch window I see AskToPlayAgain() fuction returning false and below that AskToPlayAgain() funtion returning true.

"which is a condition for do-while iteration"
Only the first instance, look where the recursive calls are returning the value to (see code I provided above)

Privacy & Terms