0
嘗試檢查cin是否獲得有效輸入(例如 - 沒有字符串或字符變量中的字符),但while循環卡住在一個無限循環,並沒有即使等待用戶輸入雖然循環不等待用戶輸入(雖然數據類型無效)
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "How many would you like to buy ? ";
int buyAmt;
cin >> buyAmt;
while (!cin) {
cin.clear();
cin >> buyAmt;
cout << "Sorry, you must enter an integer" << endl << endl;
}
}
預期結果:
How many would you like to buy ? fdssd
Sorry, you must enter an integer (asks for usr input here)
實際結果:
How many would you like to buy ? fdssd
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
Sorry, you must enter an integer
你應該'的std :: cin.ignore()'這無法讀取的問題的性質。 –