![](/img/trans.png)
[英]How do I get a C++ program to count the number of words as a user enters input?
[英]How do I prevent a runaway input loop when I request a number but the user enters a non-number?
如果輸入錯誤的類型,我需要知道如何使我的cin語句看起來不會“刪除”。 代碼在這里:
int mathOperator()
{
using namespace std;
int Input;
do
{
cout << "Choose: ";
el();
cout << "1) Addition";
el();
cout << "2) Subtraction";
el();
cout << "3) Multiplication";
el();
cout << "4) Division";
el();
el();
cin >> Input;
}
while (Input != 1 && Input != 2 && Input!=3 && Input!=4);
return Input;
}
例如,執行,輸入一個字符,它會循環不間斷,就像cin語句不存在一樣。
您必須檢查輸入是否成功並在不輸入時進行處理:
int mathOperator() {
using namespace std;
int Input;
do {
cout << "Choose: ";
el();
cout << "1) Addition";
el();
cout << "2) Subtraction";
el();
cout << "3) Multiplication";
el();
cout << "4) Division";
el();
el();
while (!(cin >> Input)) { // failed to extract
if (cin.eof()) { // testing eof() *after* failure detected
throw std::runtime_error("unexpected EOF on stdin");
}
cin.clear(); // clear stream state
cin.ignore(INT_MAX, '\n'); // ignore rest of line
cout << "Input error. Try again!\n";
}
} while (Input != 1 && Input != 2 && Input!=3 && Input!=4);
return Input;
}
如果不檢查提取是否成功,則cin將處於失敗狀態(cin.fail())。 一旦處於失敗狀態,稍后的提取將立即返回而不是嘗試從流中讀取,從而有效地使它們成為無操作 - 導致無限循環。
除非您非常確定輸入的格式是否正確,否則很少需要直接從輸入流中使用operator>>
。
通常使用std::getline
讀取一行更容易,將其放入std::istringstream
,並從那里讀取。 如果失敗,則打印/記錄錯誤消息,丟棄該行的其余部分,然后(可能)繼續執行下一行。
char Input;
do
{
// same code
}
while (Input != '1' && Input != '2' && Input != '3' && Input!='4');
return Input;
[編輯]
如果你想將char char轉換為int,你可以使用這段代碼
int i = (Input - 48);
不讀取int
,讀取char
因此cin將傳遞任何無效字符
在讀取錯誤值后,cin處於“失敗”狀態。 你必須重置這個。
您必須清除錯誤標志並清空緩沖區。 從而:
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
第二個調用“刷新”可能存在的任何數據的輸入緩沖區,以便為下一次“cin”調用做好准備。
如果你發現自己在代碼中“編寫了這兩行”,那么可以編寫一個簡單的內聯函數來替換它。
inline void reset( std::istream & is )
{
is.clear();
is.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
雖然我已經使這個函數占用任何istream,但大多數時候它只用於用戶輸入的cin
並輸入無效的東西。 如果它是無效的文件或字符串流輸入,則無法修復它,您最好只拋出異常。
我同意char很方便,因為你總是可以轉換為int,回答你為什么會發生這種情況的問題,當cin輸入被作為int執行但是輸入了char時,輸入保存在循環持續時間的輸入流,這就是為什么它似乎“消失”。
有關更多信息:請參閱Narue的帖子,網址為http://www.daniweb.com/forums/thread11505.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.