//这里填你的代码^^
//注意代码要放在两组三个点之间,才可以正确显示代码高亮哦~
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
class Monster {
public:
int id;
string imagePath;
int hp;
int attack;
int defense;
int exp;
int gold;
// 构造函数
Monster(int _id, string _img, int _hp, int _atk, int _def, int _exp, int _gold)
: id(_id), imagePath(_img), hp(_hp), attack(_atk),
defense(_def), exp(_exp), gold(_gold) {
}
// 打印方法(用于验证)
void print() const {
cout << "ID:" << id << " | 图片:" << imagePath
<< " | 血量:" << hp << " | 攻击:" << attack
<< " | 防御:" << defense << " | 经验:" << exp
<< " | 金币:" << gold << endl;
}
};
// 2. 文件读取函数
vector<Monster> loadMonsters(const string& filename) {
vector<Monster> monsters;
ifstream file(filename); //打开文件,指针指向第一行
if (!file.is_open()) {
cerr << "错误:无法打开文件 " << filename << endl;
return monsters;
}
string line; //当前行所存储的内容
getline(file, line); // 读取第一行信息,且让指针下移动一个单位长度指向第二行
while (getline(file, line)) { //从txt文件的第二行代码开始循环,读取接下来每一行的信息
istringstream iss(line); //istringstream函数会自动切分各个值,通过空格和
int id, hp, atk, def, exp, gold;
string img;
// 3. 解析每行数据
if (iss >> id >> img >> hp >> atk >> def >> exp >> gold) {
monsters.emplace_back(id, img, hp, atk, def, exp, gold);
}
else {
cerr << "警告:解析失败的行: " << line << endl;
}
}
file.close();
return monsters;
}
int main() {
// 4. 使用示例
vector<Monster> monsterList = loadMonsters("C:/Users/24203/source/repos/0413/monsters.txt");
// 验证数据
cout << "已加载 " << monsterList.size() << " 个怪物数据:" << endl;
for (const auto& m : monsterList) {
m.print();
}
return 0;
}