【发布时间】:2020-11-07 16:50:39
【问题描述】:
我在使用 while switch case 时遇到问题,我有这样的代码 我想看看用户写的不是 1,2,3,4,5,然后我想只打印“请输入选项”并要求输入新的输入,这意味着我没有想回到选择菜单,我知道它看起来很简单,我尝试使用 bool 并在 while 内部使用,但我陷入了无限循环。
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循环,所以你会陷入while循环
-
提问时请使用标点符号。
-
@Abhishek 实际上在我按 5 时返回 -1 并退出程序,但我找不到在默认值中创建循环的内容,并在输入无效时打印输入有效选项。
-
那么您可能在问题描述中添加了一些不同的内容。即使我输入 1-5 个选项,我也尝试了代码并无限运行
-
完全跑题了,但它真的让我很烦:你使用的是字符 ı,它是“LATIN SMALL LETTER DOTLESS I”(unicode C4 B1)。为什么?什么样的情况最终导致你写这个而不是
I,特别是因为我看到你也同时使用i和I。只是好奇。
标签: c++ while-loop switch-statement boolean