2016-10-25 26 views
0

我有一個簡單的C++菜單,帶有可選擇的菜單選項。如果用戶輸入除有效int之外的任何內容,如chardouble,程序將進入無限循環。我的代碼如下。如果用戶輸入無效整數,C++菜單陷入無限

#include <iostream> 

using namespace std; 

int main() 
{ 
    int selection; 
    do { 
     cout << "1) Update inventory" << endl; 
     cout << "2) Sell items" << endl; 
     cout << "3) List inventory" << endl; 
     cout << "4) Quit" << endl; 

     cout << "Please select an option: "; 
     cin >> selection; 
    } 
    while (selection != 4); 

    return 0; 
} 

爲什麼無效響應導致無限循環,怎麼能防止?

+0

你想檢查流的有效性,比如'if(!cin){/ * handle error * /}'。另請參閱[爲什麼iostream :: eof在循環條件內被認爲是錯誤的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。 – jaggedSpire

回答

-1

cin >> selection; 

將在這兩行:

cin.clear(); 
cin.ignore(); 

這將清除緩存並允許輸入可以。

+2

這不是他所問的。他詢問無效輸入,例如輸入字符而不是數字 – dwcanillas

+0

我意識到。這將解決問題。但是@ jaggedSpire是正確的。 –