我正在创建一些RPG战斗,其中程序从.txt文件读取输入。我创建了代码,但是当我想开始战斗时,它给了我一个超出范围的错误向量下标。任何人都可以帮助我如何解决这个问题?非常感谢你:)这里是代码。我将所有内容都包含进来,这样您就可以获得完整的上下文,但是我相信主要问题是在主循环中的while循环中,如果您只想跳到那里。为什么我在这里得到一个向量下标超出范围错误?
,因此,我们是在同一轨道上,txt文件为lamanite(生命值和再生点)的含量为
8 2
7 3
6 1
为nephite其
10 3
12 4
11 5
这里是我的战士.h文件中
#pragma once
#include <string>
using namespace std;
class warrior
{
public:
warrior();
warrior (int h, int r);
int getDamage() const;
void takeDamage(int damage);
int getCurrentHP() const;
void regenerate();
string tostring(int h, int r);
private:
int HitPoints;
int RegPoints;
int damage;
};
这里是我的战士CPP
#include "warrior.h"
#include <string>
#include <iostream>
warrior::warrior(int h, int r)
{
HitPoints = h;
RegPoints = r;
}
int warrior::getDamage() const
{
int damage = rand() % HitPoints;
return damage;
}
void warrior::takeDamage(int damage)
{
HitPoints = HitPoints - damage;
}
int warrior::getCurrentHP() const
{
return HitPoints;
}
void warrior::regenerate()
{
HitPoints = HitPoints + rand() % (RegPoints);
}
string warrior::tostring(int h, int r)
{
return 0;
}
我的主文件
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include "warrior.h"
using namespace std;
void main()
{
srand(time(0));
ifstream input1;
cout << "input file name nephite: ";
string filename;
cin >> filename;
input1.open(filename);
int HP1, RP1;
vector <warrior*> nephites;
while (input1 >> HP1 >> RP1)
{
nephites.push_back(new warrior(HP1, RP1));
}
cout << nephites.size() << endl;
ifstream input2;
cout << "input file name lamanite : ";
string filename2;
cin >> filename2;
input2.open(filename2);
int HP2, RP2;
vector <warrior*> lamanites;
while (input2 >> HP2 >> RP2)
{
lamanites.push_back(new warrior(HP2, RP2));
}
cout << lamanites.size() << endl;
cout << endl << "Battle" << endl;
warrior nephitesw = warrior (HP1,RP1);
warrior lamanitesw = warrior (HP2,RP2);
while ((nephites.size() > 0) && (lamanites.size() > 0))
{
int rN = rand() % nephites.size();
int rL = rand() % lamanites.size();
cout << rN << "xx" << rL << endl; // so that i know what rN and rL is
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0)) // the program can't execute this part of the code
{
nephites[rN]->takeDamage(lamanites[rL]->getDamage());
lamanites[rL]->takeDamage(nephites[rN]->getDamage());
if(lamanites[rL]->getCurrentHP() > 0)
{
lamanites[rL]->regenerate();
}
else
{
lamanites.erase(lamanites.begin() + (rL));
}
if(nephites[rN]->getCurrentHP() > 0)
{
nephites[rN]->regenerate();
}
else
{
nephites.erase(nephites.begin() + (rN));
}
}
cout << "NEP HP: " << nephites[rN]->getCurrentHP() << " " << "LAM HP: " << lamanites[rL]->getCurrentHP() << endl;
}
system ("Pause");
}
'无效main'是不是一个合法的签名,你应该使用智能指针。 – chris
如果您不知道如何在本网站上使用它们,请不要使用[RPG](stackoverflow.com/tags/RPG/info)等标签。 Stackoverflow是专业程序员(和其他人)的网站。 RPG是专业程序员几乎完全使用的语言。它占你认为理所当然的大部分业务:零售商,酒店,食品分销商,市政,仓库,银行,制造业等等。 – WarrenT