I'm relatively new to C++ (and programming in general for the most part) and I'm taking an online course which follows along by teaching with the aim of building a game. In one of the console application projects we have to write code which asks the user if the user wants play the game again.The goal for that part of the program is to ask the user to reply by typing "y" or "n" only and re-ask the question if the user responds by doing something else.
I have attempted to write code which does this and as far as I can see the code works fine. My question is, is the code I wrote valid in the following sense:
- Will the code successfully accomplish the outlined task?
- Is code like this prone to more errors if it grows later?
The code I have follows. In the main function:
.
.
.
do
{
PlayGame();
}
while (AskToPlayAgain());
And the function definition for AskToPlayAgain along with an apt description:
bool AskToPlayAgain()
{
bool Play = true;
string response = "";
cout << "Would you like to play again? y/n... ";
getline(cin, response);
if (response == "y") { }
else if (response != "n")
{
cout << "Please enter a valid response." << endl;
// We want AskToPlayAgain called again to ask for a proper response again; however,
// just calling it outside a conditional will cause the current "Play" value to be returned.
// This value is true by default and this function will return it even if "n" is entered after
// an invalid response. As such, in this case, we want this function to be called in the event
// of an invalid response which will always happen and we don't want the return value of the nested
// AskToPlayAgain function to be returned, which is true by default unless the program has successfully exited.
// Furthermore, once the nested AskToPlayAgain returns false, we want the program to exit and not return the "Play"
// (which is set to true) by the higher level AskToPlayAgain.
if (AskToPlayAgain()) { }
else { return false; }
}
else
{
Play = false;
cout << "Thank you for playing! :D" << endl;
}
return Play;
}
Is the reasoning I presented in the code comments valid? Is there a test case where this would fail? I've tried a few test cases, but all of them worked.
Many thanks for any help on this!
== ybut!= n, so inconsistent, therefore trickier. (Replaced original comment due to 5 min limit to fix typos)