【问题标题】:Guess the number - Infinite loop when bad read猜数字 - 读错时无限循环
【发布时间】:2016-10-30 07:31:24
【问题描述】:

所以我正在用 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;
}

*对不起,如果代码很优雅

如您所见,代码运行良好,直到您输入一个随机字符,如 '&' 或 'j' 或其他任何不是整数的字符...然后在 cout

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

【问题讨论】:

标签: c++ loops


【解决方案1】:

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

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

感谢 ildjarn 指出缺少的忽略声明,尽管我链接到的帖子中明确提到了该部分,但我错过了该部分!!

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      cin>>用户输入;

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

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

      【讨论】:

      • 如果不从输入缓冲区中删除无效输入,调用clear 有什么好处?
      • “重试”部分是从用户那里获得新的输入。您的答案需要说明如何首先从缓冲区中删除旧的无效输入。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多