c++ - 猜数字 - 读取错误时无限循环

标签 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;
}

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

如您所见,代码运行良好,直到您输入一个随机字符,如“&”或“j”或任何其他非整数...然后它在 cout<<"Bigger!"; 处循环。

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

最佳答案

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

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

感谢 ildjarn 指出缺少的忽略语句,我错过了那部分,尽管它在我链接的帖子中明确提到了!!

关于c++ - 猜数字 - 读取错误时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6078727/

相关文章:

loops - 如何在柏树中停止循环

javascript - 提交时 - 至少勾选一个复选框

c++ - 我在这里做错了什么?我的编译中有几个 "no match for operator"错误

c++ - Google Drive SDK/c++/Rest API 断点续传

c++ - 如何判断Qt是否调试

c++ - 如何将static_assert与sizeof和stringify结合起来?

python - 如何通过 while 循环以 python 方式避免此代码重复?

c++ - 从构造函数调用虚函数

如果 ID 存在于其他数据框中,则 Python Pandas 数据框在新列中添加 "1"

python - 在循环中调用 extract 时跳过的元素