2010-10-06 186 views
1

爲什麼當輸入錯誤輸入時無限循環?我該如何糾正?當輸入錯誤輸入時無限循環無限循環

int operation; 
    while (true) { 
     cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. "; 
     cin >> operation; 
     if (operation >= 1 && operation <= 5) break; 
     cout << "Please enter a number from 1 to 5, inclusive.\n"; 
    } 
+0

這看起來與您最近問的問題非常相似。另一個問題發生了什麼? – 2010-10-06 19:20:50

+0

啊,發佈它的人不一樣。這解釋了爲什麼我找不到它! – 2010-10-06 19:30:19

回答

0

如果你有一個cin無法解析的輸入,流將處於錯誤狀態。

這裏是你如何清除錯誤狀態,則忽略該項輸入一個例子:

int operation; 
while (true) { 
cout << "What operation would you like to perform? Enter the number corresponding to the operation you would like to perform. "; 
     cin >> operation; 
     if (cin.fail()) 
     { 
      cout << "Not a number " << endl; 
      cout << "Please enter a number from 1 to 5, inclusive.\n"; 
      cin.clear(); 
      cin.ignore(100, '\n'); 
      cin >> operation; 
     } 
     if (operation >= 1 && operation <= 5) break; 
     cout << "Please enter a number from 1 to 5, inclusive.\n"; 
    } 

注意,它試圖忽略不正確的之前清除輸入流的錯誤狀態是非常重要的字符。希望有幫助 -

+0

當到達輸入結束時,該答案從未初始化的內存中讀取,然後進入無限循環。 – 2013-06-24 21:38:07

3

在輸入流遇到錯誤後,流將處於失敗狀態。您明確地必須清除該流上的故障位並在之後將其清空。嘗試:

#include <limits> 
#include <iostream> 

... 
... 
// erroneous input occurs here 

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

您可以檢查輸入通過檢查好()不好(),失敗()或EOF的返回值升高()的錯誤。這些函數只是返回內部狀態位的狀態(如果設置了相應位,則返回true - 除了good(),顯然,如果所有內容都按順序返回)。

+0

這有效,但是當我輸入正確的輸入時,我必須按兩次輸入以接收下一個提示。我如何避免這種情況,所以我只需要輸入一次? – idealistikz 2010-10-06 19:28:27

+1

我已經回答說:檢查是否發生了錯誤,*只有*清除流。 – 2010-10-06 19:39:30