Writing object to file:

Hi,

I am trying to write object to file. The code runs fine; but the data file contains unidentified characters.

I am working on window 7 using MS studio 2010.

My code is:
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "stdafx.h"
#include <iostream>
#include <string>
//#include "fstream.h"
#include <fstream>

using namespace std;

class employee
{
string name;
float age, salary, new_salary;
public:
//We are not using the default constructor
employee();//Default Constructor
employee(string s, float a, float sal); //Explicit Constructor
void display();
float increment_the_salary(float salary, float percentage_increment);
void print_objects_to_file(string filename, employee *eptr, int no_of_objects);
//void read_objects_from_file(string filename);
~employee();//Destructor
};

//
//Defining default constructor
employee::employee()
{
name = " ";
age=0.0;
salary =0.0;

}

//Defining the explicit constructor
employee::employee(string s, float a, float sal)
{
name = string(s);
age = a;
salary = sal;
}


employee::~employee()
{
cout<<"Deleting the info.\n";
name.erase();
}

void employee::display()
{
cout<<"Name is  "<<name<<endl;
cout<<"Age is  "<<age<<endl;
cout<<"The salary is  "<<salary<<endl;
}

float employee::increment_the_salary(float salary, float percentage_increment)
{
salary = salary*(1+percentage_increment/100);
return salary;
}

int main()
{
	employee *eptr[10]; //Creating array of pointer
	cout<<"You can enter up to 10 employees \n";

	int n=0;
	int option, no_of_objects;
	string name1;
	float a, sal;

	do
	{
		cout<<"Enter the name\n";
		cin>>name1;
		cout<<"Enter the age \n";
		cin>>a;
		cout<<"Enter the salary \n";
		cin>>sal;

		eptr[n]=new employee;
		employee temp(name1, a, sal);
		*eptr[n]=temp;

		++n;
		cout<<"Do you want to enter one more employee \n";
		cout<<"Enter 1 for YES and 0 for no \n";
		cin>>option;
	}while(option);

	//Now printing all employee's information
	string filename = "Employee.dat";
	no_of_objects = n;
	employee temp;

	for (int i=0; i<n; ++i)
	{
		eptr[i]->display(); //print at display
		temp = *eptr[i];
	}


	//print_objects_to_file(string filename);
	fstream fobj;
	fobj.open(filename,ios::in|ios::out);
	int count = 0;
	fobj.seekg(0);

	do{
		fobj.write ( (char *)(eptr) , sizeof(eptr) );
		++count; 
	} while (count <= no_of_objects);
	fobj.close();

	//delete [] *eptr;*/

	system("pause");
	return 0;
}
[code]
Last edited on
please put in code tags. just click the <> on the right and put your code inbetween the two tags that appear
Last edited on
Topic archived. No new replies allowed.