C++,获得无限循环

Ann*_*Guy 1 c++ loops menu infinite switch-statement

我尝试使用开关做一个简单的菜单.我还想检查用户是否输入了有效的输入(只有1到4的int).输入-4或44可以正常使用此检查.但如果我输入类似"w"的东西,它会给我一个无限循环.我猜我需要另一个if/else if 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();
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 11

这是因为输入正在尝试获取整数.当输入不是整数时,输入保留在缓冲区中,因此下一次在循环中仍然存在相同的输入.

此外,您没有在默认情况下调用flushCin函数,而是声明它.您可能想要删除该void关键字.我想这是正确的吗?(即打电话std::cin.ignore()std::cin::clear().)