2013-11-15 118 views
1

我嘗試使用開關做一個簡單的菜單。我也想做一個檢查,如果用戶提供了有效的輸入(只有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(); 
+0

什麼是'flushCin'?您不需要按照您已經閱讀的方式刷新流。 – Mgetz

+0

嘗試更改'int enter'到'char enter'和'case 1:'到'case'1':' – Shubham

+0

兩點風格。首先:比較一個常量「bool」沒有意義;最後的條件應該是'while(!exit)'。其次,你也應該在默認情況下添加一個'break;'。 –

回答

11

這是因爲輸入試圖獲得一個整數。當輸入不是整數時,輸入保留在緩衝區中,所以下次在循環中相同的輸入仍然存在。

而且,你是不是調用在默認情況下,flushCin功能,你聲明它。您可能需要刪除void關鍵字。我猜這是對的嗎? (即調用std::cin.ignore()std::cin::clear()。)

+0

這個給我修好了,謝謝! – AnnoyedGuy

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值直接,這可能不適合的預留空間一個int並可能導致有趣的行爲。所以只要先讀入一個字符串然後解釋它。

+0

你不需要'stringstream',['std :: stoi'](http://en.cppreference.com/w/cpp/string/basic_string/stol)就可以完成這項工作。 – Mgetz

+0

@Mgetz對了,有一千種方法可以在C++中做同樣的事情;-) – Beachwalker

+0

或者在'char'中讀取,並且不要做任何轉換 – Shubham