I'm working through the book "Beginning C++ Game Programming" and I just learned about while and do loops, and if and switch statements. I want to make a program that mixes them together and does the following (without declaring any functions):
1. askes you for a choice, 1 or 2
2. asks if you want to hear the answer. If not, back to step 1; otherwise, step three.
3. Tells you the answer. Asks you if you want to hear it again. If not, it asks you if you want to play again
4. If the answer is yes, start over; if it's a no, exit.
I know I include extra preprocessor directives because I'll want to do something with them once I can get through step 1-4.
I also know I haven't included part 4 yet (because I can't get past part 1-3) and that it doesn't do anything close to what I want. I've already tried inserting more while loops and if statements in different places to get it to break up the program into the pieces I want and then go back to the correct parts of the program.
How can I get it to go through the sequence properly? And how come it doesn't matter what character I type when eliciting responses? Also, any comments about how I can notate/organize it to make it clearer would be appreciated.
Your if statement is incorrect. The if statement will be entered if either choice == '1' is true, or '2' is true. Since the statement '2' evaluates to a non-zero number, it is always true, so you always enter the if statement.
Also, the while loop: while (choice == '1' || '2')
Should be: while (choice == '1' || choice == '2')
Maybe you should use a do-while loop with the menu inside it, so that you can use the while to exit:
1 2 3 4 5 6 7
do
{
cout << "Select a choice: ";
cin choice;
//entering anything but 1 or 2 would break the loop
}while( choice == 1 || choice == 2 );
Also, the first time you get 'answer' here, you aren't actually doing anything with it:
1 2 3 4 5 6 7
cout << "y/n: ";
cin >> answer; //You're not using this before asking for input for it again
cout << " " << endl;
cout << compliment;
cout << " " << endl;
cout << "Do you want to hear that again?" << endl;
cin >> answer;
Maybe:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
cout << "y/n: ";
cin >> answer;
if( answer == 'y' )
{
cout << " " << endl; //Don't really need this, as when you press enter to input, you get a newline anyway.
cout << compliment << endl;
}
elseif( answer == n )
{
cout << " " << endl;
cout << "Don't bother then..." << endl;
}
else
cout << "Uhmmm I didn't understand your input..." << endl;
If this was in a do-while loop as above, it would then ask you for input again to select one of the switch statements.
EDIT:
Note lines 14 and 15 above. If you only have a 1 line statement, you don't need to add the {} braces around the code for that loop/if statement.