Answer to Question #180911 in C++ for Shashank Singh

Question #180911

 Define a class Employee with data members as name, emp_id, age. Write a program to write the data of three employee’s using class object. Read the records of the employee and print them to console


1
Expert's answer
2021-04-13T13:17:10-0400
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


class Employee {
private:
    string name;
    string emp_id;
    int age;

public:
    Employee(string name, string id, int age);
    bool write(ofstream &ofs) const;
    bool read(ifstream &ifs);
    void display() const;
};


Employee::Employee(string name, string id, int age) :
    name(name), emp_id(id), age(age)
{}

bool Employee::write(ofstream &ofs) const {
    try {
        ofs << name << " : ";
        ofs << emp_id << " : ";
        ofs << age << endl;
    }
    catch(...) {
        return false;
    }


    return ofs.good();
}

bool Employee::read(ifstream &ifs) {
    string new_name;
    string new_id;
    string str;
    int new_age; 

    try {
        ifs >> new_name;
        ifs >> str;
        while (str != ":") {
            new_name += " " + str;
            ifs >> str;
        }
        ifs >> new_id;
        ifs >> str;
        if (str != ":")
            return false;
        ifs >> new_age >> ws;
    }
    catch(...) {
        return false;
    }
    name = new_name;
    emp_id = new_id;
    age = new_age;
    return true;
}

void Employee::display() const {
    cout << "Employee name: " << name << endl;
    cout << "Employee id:   " << emp_id << endl;
    cout << "Employee age:  " << age << endl << endl;
}

int main() {
    Employee emp1("John Smith", "123456789", 45);
    Employee emp2("Robert Brown", "098765432", 21);
    Employee emp3("Alica Fox", "111222333", 35);

    ofstream ofs("Employees.txt");
    emp1.write(ofs);
    emp2.write(ofs);
    emp3.write(ofs);
    ofs.close();

    ifstream ifs("Employees.txt");
    emp1.read(ifs);
    emp2.read(ifs);
    emp3.read(ifs);
    ifs.close();

    emp1.display();
    emp2.display();
    emp3.display();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS