C++ 将对象的向量写入文件
如何将包含多个字符指针的对象写入文件并读回C++ 将对象的向量写入文件,c++,file,vector,stl,fwrite,C++,File,Vector,Stl,Fwrite,如何将包含多个字符指针的对象写入文件并读回 class Student { public: char* name; char* age; int size; Student(char* _name, char* _age) { name = _name; a
class Student {
public:
char* name;
char* age;
int size;
Student(char* _name, char* _age) {
name = _name;
age = _age;
size = 0;
size = strlen(_name) + strlen(_age);
}
};
我有一个学生对象的向量数组(vector
)。如何将此向量写入文件,然后再读回
有人能帮忙吗?我们能在没有
boost::serialization
帮助的情况下做到这一点吗?首先,我们更喜欢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);
}
要将其读回,您必须解析之前定义的格式:
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::UnQuyJPPT或<代码> STD::SyrdYPPTR < /C>而不是原始指针。当然可以自己实现序列化。code>boost::serialization不是由魔法精灵尘埃制成的;这只是人们编写的代码。只要你的学生是一个POD,你就可以迭代向量,将学生结构作为二进制流写入文件,并继续将其附加到文件中。阅读时,您可以从文件中读取sizeof(Student),将其强制转换为Student struct直到EOF。@Arunmu不是一个好主意。正如您所看到的,它包含指针。@molbdnilo当然他将取消对它的引用:)。他不需要序列化向量,只需要序列化数据。@Arunmu你有没有看过提供的
Student
?你必须通过const引用获取临时值,否则它不会编译。@Arunmu很好理解。在这种情况下,流当然不能是常数。我改变了我的答案,让它有了流的变量,而不是临时变量moved@Arunmu哦,你说得对<代码>istream和ostream
可以移动。所以我们可以有更漂亮的API。谢谢。不,我想说奥斯特雷姆不能动。
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);
}
auto students = readStudents(std::ifstream{"myFilename"});