【发布时间】:2015-05-06 08:38:34
【问题描述】:
我对 c++ 很陌生(这个问题是我作业的一部分)。
我需要将结构数组存储在二进制文件中并将它们读回。问题是我的结构包含std::string 字段。另一方面,我可以读取字符串,但之后什么也没有。这是我的结构定义:
struct Organization {
int id;
string name;
float paidTaxes;
};
这是我将这个结构的数组写入文件的代码:
void writeToFile(Organization *orgs, int n) {
ofstream file("orgs.bin", ios::out | ios::binary);
if (!file) { return; }
for (int i = 0; i < n; i++) {
// determine the size of the string
string::size_type sz = orgs[i].name.size();
file.write(reinterpret_cast<char*>(&orgs[i].id), sizeof(int));
// write string size
file.write(reinterpret_cast<char*>(&sz), sizeof(string::size_type));
// and actual string
file.write(orgs[i].name.data(), sizeof(sz));
file.write(reinterpret_cast<char*>(&orgs[i].paidTaxes), sizeof(float));
}
file.close();
}
这是我读回这个文件的代码部分:
count = 0;
Organization org;
ifstream file;
file.open("orgs.bin", ios::binary);
while (file.good()) {
string::size_type sz;
file.read(reinterpret_cast<char*>(&org.id), sizeof(int));
file.read(reinterpret_cast<char*>(&sz), sizeof(string::size_type));
org.name.resize(sz);
file.read(&org.name[0], sz);
file.read(reinterpret_cast<char*>(&org.paidTaxes), sizeof(float));
count++;
}
据我了解,我需要运行这个循环来确定一个文件中存储了多少个结构。当我运行调试器时,我成功读取了id 字段、字符串大小和实际字符串。但是,我从来没有得到正确的 paidTaxes 字段(float 的类型),随后的循环返回给我垃圾。
提前致谢!
【问题讨论】:
标签: c++ serialization struct fstream