我有一個簡單的C++菜單,帶有可選擇的菜單選項。如果用戶輸入除有效int
之外的任何內容,如char
或double
,程序將進入無限循環。我的代碼如下。如果用戶輸入無效整數,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;
}
爲什麼無效響應導致無限循環,怎麼能防止?
你想檢查流的有效性,比如'if(!cin){/ * handle error * /}'。另請參閱[爲什麼iostream :: eof在循環條件內被認爲是錯誤的?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。 – jaggedSpire