【发布时间】:2010-06-07 20:27:13
【问题描述】:
所以我做了一个 DOS 程序,但是我的游戏总是在我第二次运行 cin 函数时崩溃。
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
最后一行“cin >> c_action 崩溃。我使用另外两个页面。他们只是创建函数。这是编译器问题。还有为什么我的编译器在运行他的应用程序后总是关闭。有没有办法停止是吗?
【问题讨论】:
-
编写代码时的提示:绝不是编译器问题。
-
你用的是什么编译器?你能删掉一些多余的代码并将其简化为一个接近最小的例子吗?你是什么意思“崩溃”?您的编译器在运行应用程序后关闭是什么意思(编译器将在运行之前完成)?当你说崩溃的那一行是第三个输入时,你说第二个输入有什么特别的原因吗?
-
另外,我对@MSN 的重新格式化工作表示赞赏,因为原来的格式不好,但它仍然可以进行一些清理。
-
您的代码缺少 c_action 的声明。此外,您的编译器没有运行您的应用程序。您的应用程序正在操作系统中运行,当它到达终点时它会关闭。如果您不希望它停止,请在最后添加一些代码(重新启动它,或等待用户输入结束等)。
-
这是错误的:
int sizeOfEnemies = sizeof(enemies) / sizeof(int);