[英]Unable to re-access inner menu (while loop and switch)
I have the following reproducible example:我有以下可重现的示例:
#include <string>
#include <iostream>
using namespace std;
int main()
{
int choice;
bool run = true;
char inner_choice;
bool inner_run = true;
while(run != false)
{
cout << "Pick a selection" << endl;
cout << "1) Case 1" << endl;
cout << "2) Case 2" << endl;
cout << "3) Case 3" << endl;
cout << "4) Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch(choice)
{
case 1: cout << "Inside case 1" << endl;
break;
case 2: cout << "Inside case 2" << endl;
break;
case 3: cout << "Select inner menu" << endl;
cout << "a) Inner case a" << endl;
cout << "b) Inner case b" << endl;
while(inner_run != false)
{
cout << "q) q to go back main menu" << endl;
cin >> inner_choice;
switch(inner_choice)
{
case 'a': cout << "Inside inner case a" << endl;
break;
case 'b': cout << "Inside inner case b" << endl;
break;
case 'q': cout << "Going back" << endl;
inner_run = false;
break;
cin.clear();
}
}
break;
case 4: cout << "Terminate" << endl;
run = false;
break;
}
}
return 0;
}
The problem is when I select 3
for the first time, it will display the option to allow me to select the inner menu.问题是当我第一次使用 select
3
时,它会显示允许我进入 select 内部菜单的选项。 When I select q
to go back to the main menu and then to access 3
again, the option to select the inner menu is gone.当我 select
q
到 go 回到主菜单然后再次访问3
时,内部菜单的选项 select 消失了。
I thought this could be due to the cin
stream still having the input so I placed a cin.clear() but the problem persists.我认为这可能是由于
cin
stream 仍然有输入,所以我放置了一个 cin.clear() 但问题仍然存在。
Any suggestion?有什么建议吗?
You executed inner_run = false;
你执行
inner_run = false;
when q
is entered and after that inner_run
is not set to true
at anywhere.当输入
q
之后, inner_run
在任何地方都没有设置为true
。 This will prevent it from entering choice for the inner menu.这将阻止它进入内部菜单的选择。
To fix, you should set inner_run
to true
before the loop like:要修复,您应该在循环之前将
inner_run
设置为true
,例如:
inner_run = true; // add this
while(inner_run != false)
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.