C ++,获得无限循环

时间:2013-11-15 13:24:26

标签: c++ loops menu switch-statement infinite

我尝试使用开关做一个简单的菜单。我还想检查用户是否输入了有效的输入(只有int从1到4)。输入-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();

2 个答案:

答案 0 :(得分:11)

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

此外,在默认情况下,您不是调用 flushCin函数,而是声明它。您可能希望删除void关键字。我想这是正确的吗? (即,呼叫std::cin.ignore()std::cin::clear()。)

答案 1 :(得分:1)

读入字符串并尝试转换为int:

#include <sstream>
#include <string>
using namespace std;

int menu() {
        int enter;
        string str;


        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 >> str; 
        istringstream buffer(str);
        buffer >> 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);

    return enter;

}//end of menu();

如果直接输入除数字之外的其他内容,则可能不适合int的保留空间,并且可能导致有趣的行为。所以先读入一个字符串然后解释它。

相关问题