0

所以我做了一个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 崩溃。我使用了另外两个页面。他们只是创建函数。这是编译器问题。为什么我的编译器在运行他的应用程序后总是关闭。有没有办法阻止它?

4

3 回答 3

1

一些提示:如果我可以避免它们,我从不使用函数的前向声明(例如 "int create_enemyHP (int a);" )。如果你这样做,那么你的代码中有两个地方必须是正确的,你的程序才能工作。如果总是有一个“单一的事实来源” ,生活会更轻松

您是否通过调试器运行此代码?它将帮助您更快地发现问题。

于 2010-06-07T20:38:01.810 回答
0

如果你的c_action变量只是一个字符,我建议使用一个char变量,而不是一个string.
您可能想尝试这种方式,如果您仍然面临错误,您可能会给

scanf("%c", &c_action); //assuming you used a char.
于 2010-06-07T20:38:52.433 回答
0

我不明白程序是否在您键入“操作”之前或之后崩溃。因为如果它之前崩溃,那么我认为你的问题是由输入缓冲区中的空格字符引起的。

于 2010-06-07T21:30:34.493 回答