猜数字 - 读错时无限循环

时间:2011-05-21 00:10:45

标签: c++ loops

所以我猜这个用c ++编写的数字游戏看起来像这样:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0));
    int secretNumber = rand() % 100 + 1; //Generate "Random number"
    int nbrOfGuesses = 0;
    int userInput;

    cout<<"\t************************************"<<endl;
    cout<<"\t*                                  *"<<endl;
    cout<<"\t*          Guess the number!       *"<<endl;
    cout<<"\t*                                  *"<<endl;
    cout<<"\t************************************"<<endl;
    cout<<endl;
    cout << "Try to find the secret int number: " << endl;

    //While input is good
    while(cin.good())
    {
        //Do this
        do {
            cin>>userInput;
            nbrOfGuesses++;

            if (userInput>secretNumber)
                cout << "Smaller!\n";

            else if(userInput<secretNumber)
                cout << "Bigger!\n"; // <-- Infinite loop here when you enter something other than an integer

            else //Also using this as a backup of (cin.good())
                cout << "Something went wrong with the read";
                break;

        } while(userInput!=secretNumber);
                cout << "\nCongratulations! You got it in " << nbrOfGuesses << " guesses\n";
    }

    system("pause");
    return 0;
}

*如果代码非常优雅,请抱歉

正如您所看到的,代码效果很好,直到您输入像'&amp;'这样的随机字符。或者'j'或其他任何不是整数的东西......然后它在cout循环&lt;&lt;“Bigger!”;

所以我的问题是:造成这种情况的原因是什么?

3 个答案:

答案 0 :(得分:7)

检查this post,这是同样的问题。总结一下:

cin>>userInput;
if (cin.fail()) {
  cout<<"Invalid Entry, please try again."<<endl;
  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

感谢ildjarn指出丢失的忽略声明,我错过了那部分,即使它在我链接的帖子中明确提到!!

答案 1 :(得分:2)

答案 2 :(得分:0)

ci&gt;&gt;用户输入;

如果无法读取整数,则为cin流设置坏位。 你应该检查并清除后记。

if ( cin.fail() )
{
   cin.clear();
   try again
}