2012-04-18 113 views
1

該行if(!(cin.good()))cout < <「無字母」< < endl;如果我輸入字母不斷重複不停,但其他工作正常。無法說明原因。C++ cout不斷重複

#include <iostream> 
#include <cstdlib> 
#include <time.h> 
#include <cstdio> 
using namespace std; 

int main() 
{ 
    int x; 
    cout << "Please enter a number\n"; 

    srand(time(0)); 
    int y = rand(); 

    while (x != y) 
    { 
     cin >> x; 
     if (!(cin.good())) 
      cout << "No letters" << endl; 
     else if (x < y) 
      cout << "Go higher" << endl; 
     else if (x > y) 
      cout << "Go lower" << endl; 
     else 
      cout << "You win!!" << endl; 
    } 
cin.get(); 
getchar(); 
return 0; 

} 

回答

4

您的無效輸入位於輸入緩衝區中。如果你只是想扔了這一切,你可以這樣做:

... 
if (!cin.good()) 
{ 
    cout << "No letters" << endl; 
    cin.clear(); // clear error flags 
    cin.sync(); // synchronize stream with input source 
} 
... 
+1

現在它說錯誤:'else'沒有以前的'if' – Foxic 2012-04-19 00:03:51

+1

@ 30trix那麼你還有其他類型的錯字。可能忘記了最後的大括號?或者完全省略括號? – 2012-04-19 00:05:07

1

需要消耗壞輸入,因爲它會只停留在緩衝區中。

+0

不知道還是一個初學者 – Foxic 2012-04-19 00:00:05

+0

他的意思怎麼樣,就是,當你問CIN讀取一個整數,它失敗了,它離開那裏的非整數,並不斷重新嘗試讀取它。你需要讓cin讀取一些能夠成功讀取非整數的內容,比如字符串,這樣你就可以通過它。 (另請注意,x未初始化。) – 2012-04-19 00:04:18