files and streams project

all works perfectly but when data is entered it shows data and than shows error message what wrong with this code

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  #include <fstream>
#include <iostream>
#include<conio.h>
#include<string>
using namespace std;

class Employee
{
private:
	string name;
	string id;
	float salary;
public:
	Employee()
	{
		name="0";
		id="0";
		salary=0;
	}
	Employee(string name1,string id1,float salary1)
	{
		name=name1;
		id=id1;
		salary=salary1;
	}
	void set(string  name1,string id1,float salary1)
	{
		name=name1;
		id=id1;
		salary=salary1;
	}
	void get()
	{
		cout<<"Enter Data : \n";
		cout<<"Enter name :\n";
		cin>>name;
		cout<<"Enter id : \n";
		cin>>id;
		cout<<"Enter salary : \n";
		cin>>salary;
	}
	void display()
	{
		cout<<"Name : "<<name<<endl;
		cout<<"Salary : "<<salary<<endl;
		cout<<"ID : "<<id<<endl;
	}
	

};
void create(char *fname)
	{
		char choice;
		Employee temp;
		ofstream file(fname,ios::app|ios::out|ios::binary|ios::in);
		do
	{
		temp.get();
		file.write(reinterpret_cast<char*>(&temp),sizeof(temp));
		cout<<"Press Y or y to continue or any other key to exit\n";
		cin>>choice;
	}
	while(choice=='y' || choice=='Y');
}
void read(char *fname)
{
	Employee temp;
	ifstream file(fname,ios::app|ios::out|ios::binary|ios::in);
	while(file.read(reinterpret_cast<char *>(&temp),sizeof(temp)))
	{
		temp.display();
	}
}


int main()
{
	char name[20]="LAB13.txt";
	create(name);
	read(name);
	return 0;
}


Your class Employee has a C++ string which is is a pointer to a structure that holds your charaters. When you do file.write(...) you are writing the value of the pointer for the strings. Reading it back in populates the string with that value of that pointer which could be pointing to anything which is what is causing your error.
You need to not use file.write but write out each value.
I don't understand how can write each value should i use char instead of strings ?
Topic archived. No new replies allowed.