Thursday, 7 March 2019

CPP-EX15


Write a C++ program to create a class Department which contains data members as Dept_Id, Dept_Name, H.O.D., Number_Of_staff. Write necessary member functions to
i.Accept details from user for ‘n’ departments and write it in a file “Dept.txt”.
ii.Display details of department from a file.
iii.Count the number of objects stored in a file.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class dept
{
int did;
char dname[20];
char hod[15];
int nos;
public:
void accept()
{
cout<<"Enter the department id-";
cin>>did;
cout<<"\nEnter the department name-";
cin>>dname;
cout<<"\nEnter the hod-";
cin>>hod;
cout<<"\nEnter the no. of staff-";
cin>>nos;
}
void display()
{
cout<<"\nThe  department is- "<<did;
cout<<"\n The department name is- "<<dname;
cout<<"\nThe Head of department is- "<<hod;
cout<<"\nThe number of staff is- "<<nos;
}
};
void main()
{
dept d[5];
int n,i;
clrscr();
fstream file;
file.open("dept.txt", ios::in|ios::out);
cout<<"\nEnter the no. of records you want to enter-";
cin>>n;
for(i=0; i<n; i++)
{
d[i].accept();
file.write((char*) & d[i], sizeof(d[i]));
}
cout<<"\nDetails of department from the file-: ";
for(i=0; i<n; i++)
{
file.read((char*) &d[i],sizeof(d[i]));
d[i].display();
}
file.close();
getch();
}