+ 3
switch statement in C++
hello, I useed a switch statement in my program like this: Dar: cin >> alpha; switch (alpha) { case 'r': ... statement .. cout << "output : " << Area << endl; break; goto Dar; the problem is it does not show the last output because it's immedietally use goto function and goas up to Dar how can I fix this? I mean first print result and then back to menu? tahnk you
5 Answers
+ 2
@Dariyoush Your code actually does work. The problem is you put the beginning prompt before the loop, so when it loops again it doesn't display any output and is waiting for your input. That makes it appear as if it isn't doing anything, but it's simply waiting on you, that's why the code is still running afterward - it's still in the inf loop.
At the beginning where your cout that has the prompt/options, place that inside of the loop at the beginning. This will make it so you get the prompt again after you've completed one of the options.
EXAMPLE:
while (true) {
cout << "Please choose one: \n"
<< "'r' for RECTANGLE \n"
<< "'e' for ELLIPSE \n"
<< "'t' for TRIANGLE \n"
<< "'x' for EXIT the program \n"
<< endl;
cin >> alpha;
if (alpha == 'x') {
break;
}
+ 3
Easiest way to accomplish that is using a loop. Just create an inf loop that'll keep input/output open until you break/exit the loop. It'll go through your whole code and then loop back to the top to receive the next input & then go into the switch again. Just have an option for exit and then they can enter "exit" to quit or however you want it to work.
+ 3
while(true) {
cin >> alpha;
if(alpha == "exit") {
break;
}
switch (alpha)
{
case 'r':
// code
break;
}
}
+ 2
Thank you, would you please clarify a bit?
I mean in every case, should be an output and then back to the menu.
+ 2
I just posted a rough example to show you what I mean. However, if you post all of your code to me, I can show you how to fix your problem and how to go about it in the same way that you were trying to go about it.