C++猜数游戏在其他计算机上崩溃并修复无限循环

标签 c++

// Guess my number
// My first text based game
// Created by USDlades
// http://www.USDgamedev.zxq.net

#include <cstdlib>
#include <ctime>
#include <string>
#include <iostream>

using namespace std;


int main()
{

    srand(static_cast<unsigned int>(time(0))); // seed the random number generator

    int guess;
    int secret = rand() % 100 + 1; // Generates a Random number between 1 and 100
    int tries =0;

    cout << "I am thinking of a number between 1 and 100, Can you figure it out?\n";

    do 
    {
        cout << "Enter a number between 1 and 100: ";
        cin >> guess;
        cout << endl;
        tries++;

        if (guess > secret) 
        {
            cout << "Too High!\n\n ";
        }
        else if (guess < secret)
        {
            cout << "Too Low!\n\n ";
        }
        else
        {
            cout << "Congrats! you figured out the magic number in " << 
                    tries << " tries!\n";
        }
    } while (guess != secret);

    cin.ignore();
    cin.get();

    return 0;
}

我的代码在我的电脑上运行良好,但是当我的一个 friend 试图运行它时,程序崩溃了。这与我的编码有关吗?我还发现,当我输入一个字母进行猜测时,我的游戏会进入无限循环。我该如何解决这个问题?

最佳答案

“崩溃”可能与缺少运行时库有关,这将导致类似于

的错误消息

The application failed to initialize properly [...]

...要求您的 friend 安装缺少的运行时库,例如

http://www.microsoft.com/downloads/en/details.aspx?familyid=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&displaylang=en

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=a7b7a05e-6de6-4d3a-a423-37bf0912db84

选择与您用于开发应用程序的任何 Visual Studio 版本以及目标平台相匹配的版本。

至于你的应用程序进入死循环:输入一个字母后,输入流将处于错误状态,因此无法使用。类似于以下的代码将阻止这种情况:

#include <limits>
...
...
...
std::cout << "Enter a number between 1 and 100: ";
std::cin >> guess;
std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

基本上,代码 clears错误位和removes来自输入缓冲区的任何剩余输入,使流再次处于可用状态。

关于C++猜数游戏在其他计算机上崩溃并修复无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6195936/

相关文章:

c++ - 为什么我的 C++ 代码只从输入文件中读取一行?

c++ - 我怎样才能只使用静态库或共享库?

c++ - 类指针成员和异常处理

c++ - 在构造函数中使用临时参数作为默认参数

c++ - 从变量写入地址值?

c++ - Clion 的 "Call to std::pair is ambiguous"但可以编译代码

c++ - 如何在平面上获得三个非共线点? - C++

c++ - 什么是复制省略和返回值优化?

c++ - 如何安全地删除 ATL DLL 中的 std::thread

python - 如何通过 Boost.Python 从 python 文件导入函数