Skip to main content

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)

All Object Oriented Programming chapter 8 questions →