Programming

C++ Program for Reading & Writing an Object in Single Program

Write a program for reading & writing an object in a single program.

Source Code

#include<fstream>

#include<iostream>

#include<conio.h>

using namespace std;

class emp

    {

    char empname[20];

    int eno;

    float sal;

    public:

    void getdata()

        {

            cout<<"Enter name:";cin>>empname;

            cout<<"Enter employee no:";cin>>eno;

            cout<<"Enter salary: ";cin>>sal;

        }

    void showdata()

        {

            cout<<"Name: "<<empname<<endl;

            cout<<"Employee No: "<<eno<<endl;

            cout<<"Salary: "<<sal<<endl;

        }

    };

    int main()

    {

        emp em;

        cout<<"Enter the detail of employee"<<endl;

        em.getdata();

        ofstream fout("emp.dat");

        fout.write ((char *)&em,sizeof(em));

        fout.close();

        ifstream fin ("emp.dat");

        fin.read((char *)&em,sizeof(em));

        fin.close();

        em.showdata();

    getch();

}

Output

 

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.