Saturday, May 22, 2010

C++ Switch-Case Loop?

I have a program that displays a menu in a string.





char string1[]="1. Adding\n2. Subtracting\n3. Multiplying\n4.Exit Program\n\nInput Selection: ";





cout%26lt;%26lt;string1;


cin%26gt;%26gt;input;





Im using switch-case structuring. Say I choose case 1.





switch (input){


case 1:


cout%26lt;%26lt;"Please input two numbers to find the sum: ";


cin%26gt;%26gt; num1 %26gt;%26gt; num2 ;


cout%26lt;%26lt; num1 %26lt;%26lt;"+"%26lt;%26lt; num2 %26lt;%26lt;"=";


cout%26lt;%26lt; num1 + num2%26lt;%26lt;"\n\n";


cout%26lt;%26lt;string1;


cin%26gt;%26gt;input;


break;


In the console, it shows the menu and asks for input but the program closes after recieving input. Someone please help...I'm a beginner with C++ and I'm trying to learn how to loop back to the menu using the switch-case structure.

C++ Switch-Case Loop?
Ah, you used the switch instruction this time.


Using 'switch' replaces a lot of 'if' statements, but it does not loop back anywhere.


You still need to create a loop around the switch statement in order for the program to go back to the start of your program. Alternately, you can use the 'goto' instruction.


Something like this:





(This is assuming that you're using 0 to exit the program again.)





char inputnumber;





do {


(print menu)


cin %26gt;%26gt; inputnumber;


(do your switch thing here - don't check for 0)


} while (inputnumber !="0")


return 0;








OR





char inputnumber;





myloop:


(print menu)


(get input)


if (inputnumber=="0")


return 0; // exit program


(do your 'switch' without checking for 0)


goto myloop;
Reply:To loop you have to use a while-loop. Here is how you should do it:





char string1[]="1. Adding\n2. Subtracting\n3. Multiplying\n4.Exit Program\n\nInput Selection: ";





int input = 0;





while(input != 4)


{


cout %26lt;%26lt; string1;


cin %26gt;%26gt; input;





switch(input)


{


case 1:


cout%26lt;%26lt;"Please input two numbers to find the sum: ";


cin%26gt;%26gt; num1 %26gt;%26gt; num2 ;


cout%26lt;%26lt; num1 %26lt;%26lt;"+"%26lt;%26lt; num2 %26lt;%26lt;"=";


cout%26lt;%26lt; num1 + num2%26lt;%26lt;"\n\n";


cout%26lt;%26lt;string1;


cin%26gt;%26gt;input;


break;





}


}
Reply:Switch/case isn't a loop. It's like an if/then, but you can have multiple choices. (So it can replace a bunch of if/then's.) For loops you can use for/next or do/while.

survey results

No comments:

Post a Comment