Quote:Original post by Emotions06
I went back and abandoned the if/else if statements for a switch statement and I must say it looks a whole lot cleaner this way. I still don't understand how I get it to ask if you want to do it again and do it if you say yes and quit if you say no without using a goto statement (also in the tutorial I read also said don't use goto statements so I won't).
Can someone explain how to do it? Thanks.
By making a loop.
The most basic sort of loop is a while-loop. The syntax is as:
while (condition) { actions;}
It does exactly what it looks like: "while" the condition is met, the actions are performed repeatedly.
In detail: the condition is checked. If met (i.e. evaluates to true), all actions are performed. After actions are performed, the code automatically "goto"s back, and checks the condition again. This continues until the condition is not met, in which case control resumes immediately after the loop (i.e. since the condition wasn't met, the actions aren't performed, and it keeps going).
Well. You can think about it like that - in terms of how the equivalent gotos would work out. But isn't it much easier to think "as long as this is true, do that again"? :)
Now. What's your condition? Seems to be "user wants to keep going". But we don't want to check that the first time, right? We want to do the actions at least once, and check the condition at the *end* of the set of actions.
For this, we can use a do-while loop:
do { actions;} while (condition);
Same thing, except that the actions happen at least once (with the while loop, they might not happen, if the condition started out not being met).
In our case, it looks like:
do { /* all the code here that handles a math problem */} while (user_wants_to_continue());
So, how do we implement that function? Well, we need to prompt for a user's response, read the response, and interpret it as willingness-to-continue. What is the logical *type* of "willingness-to-continue"? Why, it's bool(ean), of course. Either the user wishes to continue or s/he does not.
Thus:
bool user_wants_to_continue() { cout << "Do it again? " << endl; // This is how we read a line of input robustly: std::string response; std::getline(cin, response); // We also avoid problems with "unused" input "carrying forward" to the next // time we read from cin. return response == "y" || response == "Y"; // or some more complicated interpretation, to taste.}