C ++输入运算符在1行中使用int和std :: string重载

时间:2019-04-30 08:30:11

标签: c++

我想读取一个.csv,遍历行并创建对象,然后使用输入运算符对其进行初始化。 .csv中的一行可能始终是:“ 1; king”,格式相同。现在,我希望程序读取第一行并使用Character的输入运算符设置字符的idname。如何修改我的程序来实现这一目标?

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;
}

0 个答案:

没有答案