#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;
}
私はこのコードを書いて、クラスオブジェクトのファイルからデータを読み込みました。これは出力を表示しますが、何らかのエラーを示しています。C++でのファイル操作
OUTPUT:私はそれは同じerror.Pleaseはこのエラーを取り除くために私を助けて示したの.datが、.TXT、.binファイルなどのファイル拡張子を使用して試してみました
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)
。
C++を使用している場合は、 'ifstream'、' ofstream'、 '<<' and '>>'演算子を使用してください。 – AndyG
文字列をオブジェクトとして持つためシリアル化が必要 – Raindrop7
[C++の同じクラスの複数のオブジェクトを読み書きできます](http://stackoverflow.com/questions/18186701/c-read-and-write-multiple-objects同じクラスの) – Raindrop7