【问题标题】:Unable to re-access inner menu (while loop and switch)无法重新访问内部菜单(while 循环和切换)
【发布时间】:2020-11-22 06:18:32
【问题描述】:

我有以下可重现的例子:

#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;
}

问题是当我第一次选择3时,它会显示允许我选择内部菜单的选项。当我选择q返回主菜单然后再次访问3时,选择内部菜单的选项消失了。

我认为这可能是由于cin 流仍有输入,所以我放置了一个 cin.clear() 但问题仍然存在。

有什么建议吗?

【问题讨论】:

  • 请注意,cin.clear(); 永远不会被执行,因为它在break; 之后。

标签: c++ while-loop switch-statement


【解决方案1】:

您在输入q 时执行了inner_run = false;,之后在任何地方都没有将inner_run 设置为true。 这将阻止它进入内部菜单的选择。

要修复,您应该在循环之前将inner_run 设置为true,例如:

                    inner_run = true; // add this
                    while(inner_run != false)
                    {

【讨论】:

  • inner_run 也可以在这里声明,因为它不会在其他任何地方使用。
猜你喜欢
  • 1970-01-01
  • 2020-03-08
  • 1970-01-01
  • 2020-08-13
  • 2015-03-19
  • 1970-01-01
  • 2021-10-22
  • 2015-01-04
  • 1970-01-01
相关资源
最近更新 更多