How do I save an array of objects into a file and read the saved data from the file?

I've written the following program. Now how do I save the object data saved into array to a file? and also read the saved data from the file?

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
#include <iostream>
#include <string>

using namespace std;

class Employee
{
    string employeeID;
    string name;
    string departmentName;
    int age;
    int salary;

    public:
        void setemployeeID(string id){employeeID=id;};
        void setname(string n){name=n;};
        void setdepartmentName(string dn){departmentName=dn;};
        void setage(int a){age=a;};
        void setsalary(int s){salary=s;};

        void printmployeeID(){cout<<"Employee ID: "<<employeeID<<endl;};
        void printname(){cout<<"Name: "<<name<<endl;};
        void printdepartmentName(){cout<<"Department Name: "<<departmentName<<endl;};
        void printage(){cout<<"Age: "<<age<<endl;};
        void printsalary(){cout<<"Salary: "<<salary<<endl;};
};


int main()
{
    Employee memArray[3];

    for(int i=0; i<3; i++)
    {
        cout<<"Enter Employee ID: ";
        string eid;
        cin>>eid;
        memArray[i].setemployeeID(eid);

        cout<<"Enter Name: ";
        string n;
        cin>>n;
        memArray[i].setname(n);

        cout<<"Enter Department Name: ";
        string dn;
        cin>>dn;
        memArray[i].setdepartmentName(dn);

        cout<<"Enter Age: ";
        int a;
        cin>>a;
        memArray[i].setage(a);

        cout<<"Enter Salary: ";
        int s;
        cin>>s;
        memArray[i].setsalary(s);

        cout<<"\n"<<endl;
    }

    for(int i=0; i<3; i++)
    {
        memArray[i].printmployeeID();
        memArray[i].printname();
        memArray[i].printdepartmentName();
        memArray[i].printage();
        memArray[i].printsalary();

        cout<<"\n"<<endl;
    }


    return 0;
}

Probably the easiest way would be to overload the extraction and insertion operators.

Also if your "print" functions had an ostream reference parameter you could print the items to any output stream instead of just blindly printing to the console.

void printmployeeID(std::ostream& out){ out<<"Employee ID: "<<employeeID<<endl;};

Topic archived. No new replies allowed.