2015-11-02 47 views
2

在我看來,如果輸入不是一個整數,循環將開始,並等待用戶的下一個輸入。但是,以下代碼循環使用「value for a」,並且沒有機會讓用戶鍵入其他輸入。爲什麼我在我的do while語句中遇到無限循環?

#include<iostream> 

using namespace std; 

int main() 
{ 
     int a; 
     do{ 
       cout <<"Value for a: "; 
       cin >>a; 
     } 
     while(cin.fail()); 
    return 0; 
} 
+2

'」如果輸入不是整數,循環將開始「'...循環將在任何情況下開始。你想如何擺脫循環? –

+0

看到這個答案:http://www.cplusplus.com/forum/beginner/2957/ – AsfK

回答

5

當用戶輸入錯誤輸入時,錯誤狀態爲cin設置。在清除錯誤狀態之前,您無法讀取cin中的任何內容。

您將有:

  1. 呼叫cin.clear()清除錯誤狀態,
  2. 呼叫cin.ingore()忽略該行的其餘部分。

你需要沿着線的東西:

do { 
    cout <<"Value for a: "; 
    if (cin >> a) 
    { 
     // Input was successful. 
     break; 
    } 

    // Clear the error state of the input stream. 
    cin.clear(); 

    // Ignore the rest of the line. 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
} while (true); 

並添加

#include <limits> 

能夠使用std::numeric_limits