#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