// 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;
}
我的代码在我的计算机上正常运行但是当我的一个朋友试图运行它时,该程序崩溃了。这与我的编码有关吗?我还发现,当我输入一个字母进行猜测时,我的游戏进入无限循环。我该如何解决这个问题呢?
答案 0 :(得分:5)
“崩溃”可能与缺少运行时库有关,这会导致类似于
的错误消息应用程序无法初始化 适当[...]
...要求你的朋友安装缺少的运行时库,例如
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');