I'm writing a small game for university and on launch it gives the user the choice whether to actually play the game by either entering N/Y. If the player enters 'N', I want the console to close. But I can't seem how to figure it out.
The code looks like this;
1 2 3 4 5 6 7 8 9
if (answer == "N" || "n") // if the user enters either N or n
{
cout << "Okay, Maybe next time..." << endl;
// Console Close to go here
}
elseif (answer == "Y" || "y") {
cout << "Let's play!" << endl;
}
I have tried
1 2 3 4
return 0; //Still closes console when inputting Y
system("PAUSE")
_getch();
exit;
There might be an easier way to have the Y or N handled, but I'm a beginner :)
I assume answer is declared as a string? (often a char would be used).
1 2
string answer;
cin >> answer;
Either way, the if-statement is incorrect. You need to state both parts in full,
if (answer == "N" || answer == "n")
and the same with the case for "Y" / "y".
If you use a char, things can be a little simpler - though it might seem like it is more complicated at first :)
First include this header
#include <cctype> // needed for tolower
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char answer;
cin >> answer;
answer = tolower(answer); // convert to lower case.
if (answer == 'n') // if the user enters either N or n
{
cout << "Okay, Maybe next time..." << endl;
// Console Close to go here
}
elseif (answer == 'y') // if the user enters either Y or y
{
cout << "Let's play!" << endl;
}
Note the use of single quotes for character literals 'y' and 'n'.