我的C++教授堅持在檢查輸入失敗時,必須爲每個單獨的輸入使用單獨的while()
循環。他表示,檢查多於一個輸入以下方法聚集在一個cin
說法是行不通的:C++輸入失敗:單個語句中有多個輸入
while (!good){
cout << "Enter the length and the width of the rectangle: ";
cin >> length >> width;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = true;}}
他提出的方法:以上
bool good = false;
while (!good){
cout << "Enter the length rectangle: ";
cin >> length;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = true;}}
while (good){
cout << "Enter the width rectangle: ";
cin >> width;
if(!cin){
cout << "Bad input, try again" << endl;
cin.clear();
cin.ignore(200, '\n');}
else {
good = false;}}
我的方法似乎工作就好了。如果輸入了任何一個輸入的非數字字符,則循環將提示輸入新的信息並清除故障狀態。
它是否被認爲是不正確的形式來檢查輸入失敗?我希望更清楚地瞭解爲什麼我的方法是錯誤的。如果我的方法有問題,是否有辦法檢查輸入失敗,而不用爲每個用戶輸入使用單獨的循環?我主要問,因爲我正在編寫一個程序,涉及從文件中獲取許多輸入,並且單獨檢查每個變量似乎過於乏味。我在想,一定有更好的辦法。
你的教授需要了解這種新語法(只有40歲)被稱爲一個做一段時間。 – 2015-03-24 23:57:32
爲了更接近希臘化名:更多關注,兩種代碼都不檢查「eof」標誌。 – 2015-03-24 23:59:06
您可能會發現[C++ FAQ:如何獲得std :: cin來跳過無效輸入字符?](https://isocpp.org/wiki/faq/input-output#istream-and-ignore)有用(請參閱第二個代碼示例。) – 2015-03-25 00:02:24