2012-04-18 112 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