[英]program crashes at CIN input | C++
所以我做了一个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崩溃。我使用另外两个页面。它们只是创建函数。这是编译器问题。也是为什么我的编译器在运行应用程序后总是关闭。有没有办法停止它?
一些提示:如果可以避免的话,我从不使用函数的前向声明(例如“ int create_enemyHP(int a);”)。 如果执行此操作,则代码中有两个位置必须正确才能使程序正常工作。 如果始终只有“ 单一的真理来源 ”,它将使生活更加轻松
您是否已通过调试器运行此代码? 这将帮助您更快地发现问题。
如果您的c_action
变量仅打算用作char,我建议使用char
变量,而不是string
。
您可能想尝试这种方式,如果仍然遇到错误,则可以给
scanf("%c", &c_action); //assuming you used a char.
在您输入“操作”之前或之后,我不知道程序是否崩溃。 因为如果以前崩溃过,那么我认为您的问题是由输入缓冲区中的空格字符引起的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.