C++猜数字游戏在其他计算机上崩溃并无限循环修复
C++ Guess Number game crashing on other computers and infinite loop fix
// 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!nn ";
}
else if (guess < secret)
{
cout << "Too Low!nn ";
}
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/en/details.aspx?familyid=a5c84275-3b97-4ab7-a40d-380b2af5fc2&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');
基本上,该代码清除错误位,并从输入缓冲区中删除任何剩余的输入,使流再次处于可用状态。
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- Qt 在另一个线程中无限循环
- C++代码崩溃并具有无限循环
- C++猜数字游戏在其他计算机上崩溃并无限循环修复