(这是一个家庭作业项目。)我正在尝试将 A 类的对象(包含几个字符串和整数,还有 B 类的对象列表)写入文件。然后我必须从文件中读回这些对象并显示它们的内容。我正在使用这段代码:
写作:
ofstream ofs("filestorage.bin", ios::app|ios::binary);
A d;
ofs.write((char *)&d, sizeof(d));
ofs.close();
阅读:
ifstream ifs("filestorage.bin", ios::binary);
A e(1);
while(ifs.read((char *)&e, sizeof(e))) {
cout<<e;
}
ifs.close();
<<
已经重新定义。
它将数据写入文件,然后读回,显示我想要的所有内容,但最后我得到了一个很好的胖“访问冲突”错误。我还尝试在文件中写入和读取简单变量(如 int
s)。那很好用;但是当我尝试读取一个对象或字符串时,我得到了“访问冲突”。书写接缝没问题,因为我没有出错。
你能告诉我为什么会这样吗?我该如何解决?如果有必要,我也可以发布我的 A 和 B 类。谢谢!
最佳答案
实现两个运算符<<
和 >>
为你的类(class)。
class A {
int a;
string s;
pubilc:
friend ostream& operator<< (ostream& out, A& a ) {
out << a.a << endl;
out << a.s << endl;
}
friend istream& operator>> (istream& is, A& a ) {
//check that the stream is valid and handle appropriately.
is >> a.a;
is >> a.s;
}
};
写:
A b;
ofstream ofs("filestorage.bin", ios::app|ios::binary);
ofs << b;
阅读:
fstream ifs("filestorage.bin", ios::binary);
A b;
ifs >> b;
关于c++ - 从文件中读取对象并出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257577/