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
#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();
}
Comments