I'm working on a simple card game program that I want to display all player's cards and the deck when prompted to. At the beginning of the game I have a simple question that asks if the player wants to begin play in "verbose mode" as I call it. For some reason this code works fine for me when I enter 'y' or 'n' when first prompted. If instead I press 'z' when it asks, and I enter 'y' when it loops and asks again, it exits the loop without executing the code that sets verbose to true and prints out "Beginning play in verbose mode..."
cout << "Would you like to begin play in verbose mode?(Y/N): ";
cin >> vchoice;
vchoice = tolower(vchoice);
do
{
if (vchoice == 'y')
{
verbose = true;
cout << "Beginning play in verbose mode..." << endl;
}
elseif (vchoice != 'n')
{
cout << "!!!INVALID ENTRY!!!" << endl;
cout << "Would you like to begin play in verbose mode?(Y/N): ";
cin >> vchoice;
vchoice = tolower(vchoice);
}
else
{
verbose = false;
cout << "Beginning play in normal mode..." << endl;
}
} while (vchoice != 'y' && vchoice != 'n');
Yes, I realize I *could* simply leave it at Y/N, but I prefer to have all options covered. Call me crazy, but I don't like having gaping holes in my game design.
The flow of your code is wrong. Ask the question inside a do..while loop only accepting Y or N before you can continue, then test the outcome and act on it.. something like...
#include <iostream>
usingnamespace std;
char vchoice;
bool verbose;
int main()
{
// loop until i get a Y or N
do
{
cout << "Would you like to begin play in verbose mode?(Y/N): ";
cin >> vchoice;
vchoice = toupper(vchoice);
} while (vchoice != 'Y' && vchoice != 'N');
// which one was it?
if(vchoice == 'Y') {
verbose = true;
cout << "Beginning play in verbose mode..." << endl;
}
else {
// well it wasn't Y so it was No, do something
}
return 0;
}