[英]How to write and read an object which contains pointer variables into a file in c++?Help me with the following code
[英]how to write an object that contains a list to a file c++?
我在 c++ 中读取和写入文件时遇到问题。 我的问题围绕着尝试保存具有属性向量的 object。 调试时,object 似乎存储正确,但在读回时,向量值为 0,但向量的大小是正确的。 在做了一些研究之后,我知道我可能应该在某个地方进行序列化。 我的问题是我不知道我的所有研究如何以及我的所有研究都将我引向图书馆提升。 有人可以指出我正确的方向吗? 以下是我的代码片段。
我的数据.h
class MyData {
public:
std::vector<float> scores;
MyData(vector<float> scores);
MyData();
};
像这样写入文件:
MyData mdata(*vector here*);
std::ofstream file_obj("foo.txt");
// Writing the object's data in file
file_obj.write((char*)&mdata, sizeof(mdata));
std::cout << "data saved!";
像这样读:
MyData obj;
// Reading from file into object "obj"
file_obj.read((char*)&obj, sizeof(obj));
// Checking till we have the feed
while (!file_obj.eof()) {
// Checking further
file_obj.read((char*)&obj, sizeof(obj));
}
在这种简单的情况下,您不需要提升。 问题是当您应该编写浮点数时,您正在编写 object (这是没有意义的)。 您还需要写入浮点数,以便在您回读时知道要读取多少。 像这样的写作
// how many floats
size_t number_of_floats = scores.size();
// write the number of floats
file_obj.write((char*)&number_of_floats, sizeof(size_t));
// write the floats themselves
file_obj.write((char*)scores.data(), number_of_floats * sizeof(float));
和这样的阅读
// read the number of floats
size_t number_of_floats;
file_obj.read((char*)&number_of_floats, sizeof(size_t));
// adjust vector to correct size for the number of floats
scores.resize(number_of_floats);
// read the floats
file_obj.read((char*)scores.data(), number_of_floats * sizeof(float));
向量通常由一个包含指向堆分配数组的指针的小结构组成。 字符串是相似的。 写 object 只写结构,不写动态数据。 为此,您需要使用boost serialization 之类的东西。 这将以可以重新加载的形式表示数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.