如何解决C ++ Guess Number游戏在其他计算机上崩溃并无限循环修复
||// 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;
}
我的代码可以在我的计算机上正常运行,但是当我的一个朋友尝试运行它时,程序崩溃。这和我的编码有关吗?我还发现,当我输入字母进行猜测时,我的游戏进入了无限循环。我该如何解决这个问题?
解决方法
“崩溃”可能与缺少运行时库有关,这将导致类似于以下内容的错误消息
应用程序初始化失败
适当地[...]
...要求您的朋友安装缺少的运行时库,例如
http://www.microsoft.com/downloads/zh-CN/details.aspx?familyid=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&displaylang=en
http://www.microsoft.com/downloads/zh-CN/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\');
基本上,代码清除错误位,并从输入缓冲区中删除所有剩余的输入,从而使流再次处于可用状态。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。