C++,得到一个无限循环

标签 c++ loops menu switch-statement infinite

我尝试使用 switch 做一个简单的菜单。我还想检查用户是否进行了有效输入(仅限 1 到 4 的整数)。输入 -4 或 44 可以很好地处理此检查。但是如果我输入类似“w”的东西,它会给我一个无限循环。 我猜我需要另一个 if/else with if (!cin) blabla else 继续切换。 但我不确定我该怎么做,否则正在启动开关。

 int menu() {
        int enter;
        bool exit = false;
        do {
            cout << "Wie soll angefangen werden: " << endl; //Enter your choice
            cout << "1 - Spiel starten" << endl; // do game();
            cout << "2 - Highscore " << endl; //do score();
            cout << "3 - Quiz starten " << endl; //do quiz();
            cout << "4 - Ende " << endl; //end the programm

        cin >> enter; 

        switch (enter) {
            case 1:
                game();
                break;
            case 2:
                score();
                break;
            case 3:
                showQuizDialog();
                break;
            case 4:
                exit = true;
                break;
            default:
                cout << "Keine gültige Eingabe, nochmal: " << endl; //invalid input, again
                void flushCin();
        } //end of switch
    } while (exit == false); 

}//end of menu();

最佳答案

这是因为输入试图得到一个整数。当输入不是整数时,输入将保留在缓冲区中,因此下一次循环中相同的输入仍然存在。

此外,在默认情况下,您不是调用flushCin 函数,而是声明它。您可能想要删除 void 关键字。我想它做对了? (即调用 std::cin.ignore()std::cin::clear() 。)

关于C++,得到一个无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20002137/

相关文章:

c++ - 自动工具检查 C++11

c++ - `new` 中的 `new int;` 是否被视为运算符?

c++ - 从 C 代码调用 C++ 方法

c++ - 为什么这段代码用 g++ 编译需要这么长时间?

CountChars数组字符串循环函数字母出现次数

c# - 将 ToolStripMenu 重新用于 ToolStrip 或 ContextMenuStrip?

css - 将淡入淡出动画添加到纯 CSS 移动菜单抽屉

c# - c# 和 c++ 中反向循环的奇怪行为

java - while循环不会改变变量的值

macos - 左键与右键单击状态栏项目 Mac Swift 2