C++,而switch case则在默认值内进行循环



我在使用while switch caseı时遇到了一个问题我想看看用户是否写了1,2,3,4,5以外的内容,然后我想只打印";请输入选项";并要求提供新的输入,这意味着我不想回到选择菜单,我知道这看起来很容易,我试图使用bool并在内部使用,但我陷入了无限循环。

cout << "Welcome to program." << endl;
while (true) 

cout << "Please make a choice from the following menu: " << endl;
cout << " Press 1 for this.... ," << endl;
cout << "Press 2 for this.... . ," << endl;
cout << "Press 3 for this.... . ," << endl;
cout << "Press 4 for this.... . ," << endl;
cout << "Press 5 for this.... ." << endl;
cout << endl;
cin >> num;
cout << endl;
switch (num)
{
case 1: 

cout << "Success!" << endl;
break;
case 2 : 
cout << "You presed 2 " << endl;
break;
case 3 : 
cout << "You pressed 3 " ;
break;
case 4: 
cout << "You pressed 4 " ;
cout << endl;
break;
case 5 : 
cout << "You pressed 5 " ;


default:
cout << "Please enter a valid option!" << endl; // only print this while user write other than cases
cin >> num;

cout << endl;
while (true) 

我可以看到,在while循环之后没有使用括号,那么你希望它如何正确地循环呢。只有在没有括号的情况下,它才会执行下一行代码。因此,将您的代码封装在while(true)

除此之外,你永远不会脱离while循环,所以你会被困在while循环中。while循环中没有任何条件可以随时将你从循环中打断。切换用例块中的break只会使您脱离切换用例块,但您仍将留在while循环中。所以,如果你想突破循环,你必须突破开关块之外的循环。

您可能会维护一个标志,指示是否执行选项1、2、3、4、5中的任何一个,然后您可以脱离循环。或者,您可以想出一个适合您的用例的逻辑。我只是指出了你哪里出了问题。

正确的代码-

cout << "Welcome to program." << endl;
int num=3;
while (true) {
if(num>=1&&num<=5){
cout << "Please make a choice from the following menu: " << endl;
cout << " Press 1 for this.... ," << endl;
cout << "Press 2 for this.... . ," << endl;
cout << "Press 3 for this.... . ," << endl;
cout << "Press 4 for this.... . ," << endl;
cout << "Press 5 for this.... ." << endl;
cout << endl;
}
cin >> num;
cout << endl;
switch (num)
{
case 1:         
cout << "Success!" << endl;
break;
case 2 : 
cout << "You presed 2 " << endl;
break;
case 3 : 
cout << "You pressed 3 " ;
break;
case 4: 
cout << "You pressed 4 " ;
cout << endl;
break;
case 5 : 
cout << "You pressed 5 " ; 
break;                  
default:
cout << "Please enter a valid option!" << endl; // only print this while user write other than cases
continue;
}
}

上面的代码将循环,直到用户输入一个无效的选项,并且只有在用户输入了正确的选项后才脱离循环。

任何你不想重复的事情,都不要放在循环中。就这么简单。显示完整菜单和循环外的第一个提示。如果输入了错误的数字,您的默认案例将仅打印其消息。我还缩小了开关,因为所有额外的打字都是不必要的。[[fallthrough]]是一个很好的工具,但它需要C++17。

如果你想要的只是一个有效的输入,那么你真的不应该为while (true)无限循环而烦恼。只要您的输入无效,就进行迭代。

#include <iostream>
int main() {
int num = 0;
std::cout << "Welcome to the program.n";
std::cout << "Please make a choice:n"
<< "1.n2.n3.n4.n5.nn"
<< "Please enter option: ";
while (num < 1 || num > 5) {
std::cin >> num;
switch (num) {
case 1:
std::cout << "Success!n";
break;
case 2:
[[fallthrough]];  // C++17 needed for this, otherwise leave empty
case 3:
[[fallthrough]];
case 4:
[[fallthrough]];
case 5:
std::cout << "You pressed " << num << ".n";
break;
default:
std::cerr << "Invalid entry!nPlease enter a **valid** option: ";
}
}
}

最新更新