- 2074 Chaitra · 4 marks
Write and display 10 employees using file
Short answer
Define an Employee class with id, name, salary and methods to input, write to ofstream, read from ifstream, and display. In main, write 10 records to employee.txt, one per line, then reopen and read/display each record in a loop until end-of-file.
Write a program to write the information of 10 employee in a file. And also display their details in console.
The program writes 10 employee records to a text file, then reopens the file and displays them.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Employee {
int id;
string name;
float salary;
public:
void getData() {
cout << "Enter id, name, salary: ";
cin >> id >> name >> salary;
}
void writeTo(ofstream &fout) {
fout << id << " " << name << " " << salary << endl;
}
bool readFrom(ifstream &fin) {
return (fin >> id >> name >> salary) ? true : false;
}
void display() {
cout << id << "\t" << name << "\t" << salary << endl;
}
};
int main() {
Employee e;
ofstream fout("employee.txt");
for (int i = 1; i <= 10; i++) {
cout << "Employee " << i << endl;
e.getData();
e.writeTo(fout);
}
fout.close();
ifstream fin("employee.txt");
cout << "\nID\tName\tSalary\n";
while (e.readFrom(fin))
e.display();
fin.close();
return 0;
}
Names are read with >>, so they should not contain spaces. The while loop stops automatically at end of file.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Manager derived from person and employee · Object Oriented Programming, chapter 6
- Student records file with CRN search · Object Oriented Programming, chapter 8
- Random access file transaction processing · Object Oriented Programming, chapter 8
- Student file displayed in descending marks order · Object Oriented Programming, chapter 8
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8
- Employee text file; sort into binary file · Computer Programming, chapter 10
- Sort employee structures by salary · Computer Programming, chapter 8 · asked 2×
- Employees with salary above 10,000 · Computer Programming, chapter 8
- Display records sorted by name from file · Computer Programming, chapter 10