程序在CIN输入时崩溃| C ++

时间:2010-06-07 20:27:13

标签: c++ cin

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

3 个答案:

答案 0 :(得分:1)

一些提示:  我从不使用函数的前向声明(例如“int create_enemyHP(int a);”),如果我可以避免它们。如果这样做,那么代码中有两个位置必须正确才能使程序正常工作。如果总有“single source of truth

,它会让生活更轻松

您是否通过调试器运行此代码?它可以帮助您更快地找到问题。

答案 1 :(得分:0)

如果您的c_action变量仅用作字符,我建议您使用char变量,而不是string。 您可能想尝试这种方式,如果您仍然遇到错误,可以给出

scanf("%c", &c_action); //assuming you used a char.

答案 2 :(得分:0)

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