how to write and read classes that contains string in a file

example

class person
{
string name;
int age;
};

i want to write it's objects and read them from the file.

while reading objects from file it is giving error segmentation fault(core dumped)

the same method works when i use this definition

class person
{
char name[25];
int age;
};

well i am using this function to write objects

ofstream offill;
offill.open(filename);
person p;
offill.write((char*)&p,sizeof(p));

and to read

ifstream iffill;
iffill.open((char*)&p,sizeof(p));

any suggestions or solutions??

sorry for bad english
I would recommend using structures instead of classes if you are planning to keep all the data public. Also, I'm not sure if you already have this but you need to #include <fstream>
It's really hard to tell since you are missing half the program. Try uploading the whole thing and I could help from that.
A few things.

You need to initialize your variable p with some values, otherwise you create only an empty file.

You need to open your iffil stream properly. ifstream iffill(filename) then you can use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream> 
#include <fstream>
#include <string.h>

using namespace std;

class person
{
public:
  char name[25];
  int age;
};

int main ()
{
  const char *filename = "C:\\Temp\\person.bin";
  person p;

  strcpy(p.name, "Anna Lazareva");
  p.age = 22;
  
  ofstream offill;
  offill.open(filename);

  offill.write((char*)&p,sizeof(p));

  ifstream iffill(filename);
  person p2;

  iffill.read((char*)&p2, sizeof(p2));
  cout << p.name << "\t" << p.age << endl;
  system("pause");
}

Topic archived. No new replies allowed.