猜数字 - 无限循环时坏读 [英] Guess the number - Infinite loop when bad read

查看:91
本文介绍了猜数字 - 无限循环时坏读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使这个猜数字游戏在c + +,看起来像这样:

So I am making this Guess the number game in c++ that looks like this:

#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;
}

*对不起,如果代码是非常优雅的

*Sorry if the code is note very elegant

正如你所看到的,代码工作得很好,直到你输入一个随机的符号'&'或'j'或任何不是一个整数的其他...然后它循环在cout& <Bigger!;

As you can see, the code works great until you enter a random caracter like '&' or 'j' or anything else that isn't an integer...Then it loops at cout<<"Bigger!";

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

So my question is: What is causing this?

推荐答案

检查此帖< a>,这是大致相同的问题。总结:

Check this post, it is about the same problem. To summarize:

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

感谢ildjarn指向缺少的忽略语句,在帖子中清楚提到我链接到!!

Thanks ildjarn for pointing the missing ignore statement, I missed that part even though its clearly mentioned in the post I linked to!!

这篇关于猜数字 - 无限循环时坏读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆