Reputation: 135
How do I loop this switch case? I need to be able to loop back to the menu selection after after each switch case to make a new selection. Help?
int _tmain(int argc, _TCHAR* argv[]){
char choice;
showWelcome(); // Show Welcom Screen
showMenu(); // Show Menu Screen
cin >> choice; // Make Menu Secection
{
switch(choice)
{
case'1':
seriesCalc();
break;
case'2':
parallelCalc();
break;
case'q':
system("cls");
break;
default:
break;
return 0;
}
}
} // end main
Upvotes: 0
Views: 3651
Reputation: 76438
Write a function to encapsulate the real work and call it.
for(;;) {
cin >> choice;
if (!cin || do_user_command(choice) == cmd_exit)
break;
}
Upvotes: 0
Reputation: 425
int _tmain(int argc, _TCHAR* argv[]){
char choice;
showWelcome(); // Show Welcom Screen
showMenu(); // Show Menu Screen
**while**(cin >> choice) // Make Menu Secection
{
switch(choice)
{
case'1':
seriesCalc();
break;
case'2':
parallelCalc();
break;
case'q':
system("cls");
break;
default:
break;
return 0;
}
}
} // end main
std::cin will return a positive value when the input is valid.
Upvotes: 0
Reputation: 25725
while(cin){
cin >> choice; // Make Menu Secection
{
switch(choice)
{
case'1':
seriesCalc();
break;
case'2':
parallelCalc();
break;
case'q':
system("cls");
break;
default:
break;
return 0;
}
}
}
Also if you do not mind the goto
statement:
back: cin >> choice; // Make Menu Secection
{
switch(choice)
{
case'1':
seriesCalc();
break;
case'2':
parallelCalc();
break;
case'q':
system("cls");
break;
default:
break;
return 0;
}
goto back;
}
However if you plan on going the goto
way: remember
Upvotes: 2
Reputation: 639
int _tmain(int argc, _TCHAR* argv[]){
char choice;boolean again=true;
showWelcome(); // Show Welcom Screen
showMenu();
while(again){ // Show Menu Screen
cin >> choice; // Make Menu Secection
{
switch(choice)
{
case'1':
seriesCalc();
break;
case'2':
parallelCalc();
break;
case'q':
system("cls");
break;
default:
again=false;
}
}
return 0;
}
}
Upvotes: 0
Reputation: 762
Use a while loop or a do-while loop. You may want to add the possibility for exit in the switch statement, i.e. while ( loop ) {
and case 'q': loop = false
.
This is good because it doesn't automatically quit the program afterwards.
Upvotes: 0