#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class telephone
{
string name;
long number;
public :
void getdata();
void display();
};
void telephone :: getdata()
{
cout<<"Enter the name : ";
getline(cin,name);
cout<<"Enter the number : ";
cin>>number;
}
void telephone :: display()
{
cout<<"1. Name : "<<name<<endl;
cout<<"2. Number : "<<number<<endl;
}
int main()
{
fstream f;
telephone p,q;
f.open("dir.txt",ios::out);
p.getdata();
f.write((char*)&p,sizeof(telephone));
f.close();
f.open("dir.txt",ios::in);
while(f.read((char*)&q,sizeof(telephone)))
{
q.display();
}
f.close();
return 0;
}
我已经写了这段代码来写入和读取类object.be上的文件的数据。它显示输出但显示一些错误。C++将数据拷贝到类对象的文件处理
OUTPUT:
Enter the name : rahul
Enter the number : 234546
1. Name : rahul
2. Number : 234546
*** Error in `./a.out': double free or corruption (fasttop): 0x08f861a8 ***
Aborted (core dumped)
我以文件扩展比如后缀名为.txt,.bin和.DAT,但它显示了同样的error.Please帮我消除这种误差尝试。
如果您使用C++,请使用'ifstream','ofstream'和''<<' and '>>'操作符。 – AndyG
您需要序列化,因为有一个字符串作为对象 – Raindrop7
[C++读取和写入同一类的多个对象]的可能重复(http://stackoverflow.com/questions/18186701/c-read-and-write-multiple-objects同类) – Raindrop7