[英]C++ Loop within Switch Case statement
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
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: 如果你不介意goto
语句:
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 但是如果你打算去goto
方式:记住
Use a while loop or a do-while loop. 使用while循环或do-while循环。 You may want to add the possibility for exit in the switch statement, ie while ( loop ) {
and case 'q': loop = false
. 您可能希望在switch语句中添加exit的可能性,即while ( loop ) {
和case 'q': loop = false
。
This is good because it doesn't automatically quit the program afterwards. 这很好,因为它之后不会自动退出程序。
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;
}
}
int _tmain(int argc, _TCHAR* argv[]){ 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. 当输入有效时,std :: cin将返回正值。
Write a function to encapsulate the real work and call it. 编写一个函数来封装实际工作并调用它。
for(;;) {
cin >> choice;
if (!cin || do_user_command(choice) == cmd_exit)
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.