写对象的传染媒介到文件

时间:2015-12-09 08:38:31

标签: c++ file vector stl fwrite

如何编写一个包含多个指向文件的char指针的对象并回读?

vector<Student*>

我有一个Student对象的矢量数组(boost::serialization)。如何将此向量写入文件然后回读?

有人可以帮忙吗?我们可以在没有package main import "fmt" type User struct { UserName string Category string Age int } type Users []User func (u Users) NameList() []string { var list []string for _, user := range u { list = append(list, user.UserName) } return list } func main() { users := Users{ User{UserName: "Bryan", Category: "Human", Age: 33}, User{UserName: "Jane", Category: "Rocker", Age: 25}, User{UserName: "Nancy", Category: "Mother", Age: 40}, User{UserName: "Chris", Category: "Dude", Age: 19}, User{UserName: "Martha", Category: "Cook", Age: 52}, } UserList := users.NameList() fmt.Println(UserList) } 的帮助下完成这项工作吗?

1 个答案:

答案 0 :(得分:1)

首先,std::string优先于char*。你不再需要那么大了。也更喜欢在构造函数中初始化而不是在构造函数体中赋值:

class Student {
    public:
        std::string name;
        std::string age;

        Student(const std::string& _name, const std::string& _age) : 
            name{_name}, age{_age}
        {};

        auto size() const -> size_t {
            return name.size() + age.size();
        };
};

回到你的问题。在尝试存储复杂结构之前,必须定义格式。在这种情况下,我选择了一个简单的CSV,用分​​号作为字段分隔符,没有引号。

void writeStudents(std::ostream& o, const std::vector<Student*>& students) {
    for(auto s: students) {
        o << s->name << ';' << s->age << '\n';
    }
}
void writeStudents(std::ostream&& o, const std::vector<Student*>& students) {
    writeStudents(o, students);
}

现在你可以使用`std :: ofstream``生成那个csv:

writeStudents(std::ofstream{"myFilename"}, students);

要阅读它,您必须解析之前定义的格式:

auto readStudents(std::istream& i) -> std::vector<Student*> {
    auto students = std::vector<Student*>;
    auto line = std::string{};

    while( std::getline(i, line) ) {
        auto pos = line.find_first_of(';');
        students.push_back(new Student{std::string{line, 0, pos},
                                       std::string{line, pos+1}});
    }

    return students;
}
auto readStudents(std::istream&& i) -> std::vector<Student*> {
    return readStudents(i);
}

现在,您可以使用std::ifstream

阅读文件
auto students = readStudents(std::ifstream{"myFilename"});

注意:此答案中的所有代码均未经过测试。当然要小心虫子。我也为你留下了错误处理,因为我不想用那种噪音污染答案。

顺便说一句:你如何确保学生的记忆能够正确管理?考虑使用std::unique_ptr<>std::shared_ptr<>而不是原始指针。

相关问题