C++ program to store records of objects of class to a FILE

//program to store record of 5 employees to a file named employee.txt
//class Employee with id,name,address and salary as data members

#include <iostream>
#include <fstream>
using namespace std;
class Employee
{
  public:
    int id;
    char name[20],address[20];
    float salary;
    void readRecord()
    {
      cout<<"Enter ID: ";
      cin>>id;
      cout<<"Enter name: ";
      cin>>name;
      cout<<"Enter address: ";
      cin>>address;
      cout<<"Enter salary: ";
      cin>>salary;
    }
};
int main()
{
  Employee e[5];
  int i;
  for(i=0;i<5;i++)
  {
    cout<<"Enter record "<<i+1<<":"<<endl;
    e[i].readRecord();
  }
  ofstream out("employee.txt");
  cout<<"Writing to a file.....";
  for(i=0;i<5;i++)
  {

    out<<e[i].id<<endl<<e[i].name<<endl<<e[i].address<<endl<<e[i].salary<<endl<<endl;
  }
  out.close();
  return 0;
}

No comments:

Post a Comment