我想读取一个.csv,遍历行并创建对象,然后使用输入运算符对其进行初始化。 .csv中的一行可能始终是:“ 1; king”,格式相同。现在,我希望程序读取第一行并使用Character
的输入运算符设置字符的id
和name
。如何修改我的程序来实现这一目标?
Character.h:
#pragma once
#include <iostream>
class Character
{
public:
Character() {}
Character(int id, std::string name);
std::string getName();
private:
int id;
std::string name;
friend std::ostream & operator << (std::ostream &out, const Character &c);
friend std::istream & operator >> (std::istream &in, Character &c);
};
Character.cpp重载方法:
std::istream &operator>> (std::istream& input, Character& c)
{
input >> c.id;
std::string s(std::istreambuf_iterator<char>(input), {});
return input;
}
FileReader方法:
std::ifstream file;
file.clear();
file.open("assets/characterCards.csv");
if (file.is_open())
{
std::string line;
while (std::getline(file, line)) {
int pos = line.find(";");
std::string input = line.replace(pos, 1, "");
std::stringstream sStream(line);
Character c;
sStream >> c;
}
}
修改
我尝试了以下重载,但是这在c.name上产生了错误代码C2679
std::istream &operator>> (std::istream& input, Character& c)
{
input >> c.id;
input >> c.name;
return input;
}