C++, getting a infinite loop

后端 未结 2 2040
半阙折子戏
半阙折子戏 2021-01-15 20:55

i try to do a simple menu using switch. I also want to do a check if the user made a valid input (Only int from 1 to 4). Entering -4 or 44 is working fine with this check. B

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-15 21:24

    Read into a string and try to convert to int:

    #include 
    #include 
    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();
    

    If entering other things than numbers into an int value directly this might not fit into the reserved space of an int and can result in funny behaviour. So just read into a string first and then interpret it.

提交回复
热议问题