我嘗試使用開關做一個簡單的菜單。我也想做一個檢查,如果用戶提供了有效的輸入(只有int從1到4)。輸入-4或44對此檢查正常工作。但是如果我輸入類似「w」的東西,它會給我一個無限循環。 我猜我需要另一個if/else if(!cin)blabla else else with switch。 但我不知道我是怎麼做的,其他人正在開關。C++,獲得無限循環
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'?您不需要按照您已經閱讀的方式刷新流。 – Mgetz
嘗試更改'int enter'到'char enter'和'case 1:'到'case'1':' – Shubham
兩點風格。首先:比較一個常量「bool」沒有意義;最後的條件應該是'while(!exit)'。其次,你也應該在默認情況下添加一個'break;'。 –