Question

In: Computer Science

Your assignment is to write a C++ program to read a text file containing the information...

Your assignment is to write a C++ program to read a text file containing the information of the employees of a company, load them into memory and perform some basic human resources operations. This assignment will help you practice: multiple file programming, classes, public and private methods, dynamic memory allocation, constructors and destructors, singly linked list and files.

Implementation

This lab assignment gives you the opportunity to practice creating classes and using dynamic memory in one of the required classes. There are two classes to implement Employee and Company. #the Company will hold a linked list of Employees. This list of employees is modeled using linked nodes of Employee* (pointers to Employees). These employees are created dynamically when they are added to the list.

You will create the following files:

  • menu.cpp: contains your main function
  • employee.h: contains the Employee class declaration
  • employee.cpp: contains the Employee class method definitions
  • company.h: contains the Company class declaration
  • company.cpp: contains the Company class method definitions

Class Descriptions

Employee

Notice there are no changes from previous Employee implementation

Access Member Description
Private _id: unsigned int ID
Private _name: string Name
Private _salary: double Salary
Private _managerId: unsigned int Manager ID
Public Employee(unsigned int, const string&, double, unsigned int=0 Creates an employee using the values given by the parameters. The last parameter represents the manager ID. If the name parameter is an empty string, the constructor should initialize the name to “***”
Public Employee(const Employee&) Copy constructor for Employee
Public GetID(): unsigned int Accessor for ID
Public GetName(): string Accessor for name
Public GetSalary():double Accessor for salary
Public GetManagerId(): unsigned int Accessor for Manager ID
Public ToString():string Returns a string representation of the Employee. (see after the table for the details on this method)
Public Raise(double):void Gives a raise to the employee, adding the specified amount to his or her current salary.
Public Equals(const Employee&) Returns true if the employee specified by the parameter has same ID as current object.
Public Read(istream&):bool Reads an employee from the istream returning true/false depending on whether read was successful.
Public Write(ostream&):void Writes the information about an employee, separated by spaces, to the ostream.
Public ~Employee() Destructor, empty

Company

Access Member Description
Private struct Node{Employee* data; Node* next; } Represents the node type that will become each of the links of the linked list.
Private _head: Node* Head of the list, is the pointer to the first element of the list.
Private _size: unsigned int The number of actual employees in the list. In the beginning, there are no employees.
Private Company(const Company&) Copy constructor private to prevent copies from 'outside' the class.
Public Company() Constructor for Company. Sets the _size to zero, initializes _head to nullptr.
Public AddEmployee(unsigned int, const string&, double, unsigned int=0): bool Adds an employee to the list (to the correct position, the list must always be sorted). The parameters specify the information about the employee. Returns true if it was able to add it, false otherwise.
Public AddEmployee(const Employee&): bool Adds the specified employee to the list(to the correct position, the list must always be sorted). Returns true if it was able to add it, false otherwise.
Public FindById(unsigned int): int Uses binary search to find an employee using the ID given in the parameter. Returns -1 if the employee is not found. If it is found returns the position of that employee.
Public FindByName(const string&, unsigned int=0) Uses linear search starting from the position specified by the second parameter to find the first occurrence of the given name in the Array. Returns -1 if the employee is not found. If it is found returns the position of that employee.
Public Read(istream&):int Reads an istream and extracts all the employees’ data from there, and adds the employees to existing list of employees. Returns the number of employees read.
Public Write(ostream&):int Writes all the available employees to the ostream. Returns the number of employees written.
Public IsFull():bool Always returns false.
Public Get(unsigned int): Employee* Returns a pointer to the Employee at the position specified by the parameter. If the position is invalid, it returns nullptr. The referenced object belongs to the object and should not be “deleted” by the client.
Public GetEmployeeCount():unsigned int Returns the number of employees in the Company (_size)
Public ~Company() Frees the memory by releasing all the dynamically created employees in the array.

Employee::ToString(), returns a formatted string following the following format:

ID: 1 Name: Peter Salary: 250 Manager ID: 0

Widths:

  • ID: 4
  • Name: 10
  • Salary: 10
  • Manager ID: 4

Program Menu

Your program should output the following menu:

1. Load from File
2. Save to File
3. List all Employees
4. Search by Name
5. Search by ID
6. Find Employee Boss Information
7. Add new Employee
8. Check if Database is Full
9. Exit
Menu Option Description
Load a Company File Asks the user for the file name containing the employee’s information. TXT files containing sample company information are included with this Lab document.
Save Company Data to File Saves the current information in memory to a file. The program asks the user for the file name where the user wants to save this.
List all Employees Lists all the employees stored in memory. Uses company ToString method to display them.
Search by Name The user inputs a name, then, using the method FindFirstByName the program displays all employees with that name using ToString method.
Search by ID The user inputs an ID, then, using the method FindById the program displays the employee with that ID using ToString method or that it did not find that ID.
Find Employee Boss Information The user inputs an ID, then, using the method FindById the program displays the employee ID using GetID method or that it did not find that ID. Once the employee is found, gets the manager’s ID, and with it searches that ID and gets the manager’s rest of the information. Displays the manager information using ToString method.
Add New Employee Requests the user to enter the following information about the employee: ID, name, salary and manager ID. Manager ID is zero for employees without boss. Only adds employees if it fits in the array! Only adds employees with ID that is not already in the list
Check if Database is Full Displays a message indicating if the database is full, or not full.
Exit Exits the program

Solutions

Expert Solution

Employee class Read and Write is not implemented as Company class is implementing same functions. Both will be same. As requested, I created a new function FindByIdBinarySearch(), you can use either Find functions, or you can replace existing FindById with that of FindByIdBinarySearch.

Employee.cpp

#include "Employee.h"
#include <sstream>
#include <iomanip>
using namespace std;

Employee::Employee(const Employee &emp)
{
   this->_id = emp._id;
   this->_name = emp._name;
   this->_salary = emp._salary;
   this->_managerId = emp._managerId;
}

uint Employee::getId() const
{
   return _id;
}

uint Employee::getManagerId() const
{
   return _managerId;
}

const string& Employee::getName() const
{
   return _name;
}

Employee::Employee(uint id, const string &name, double salary, uint managerId)
{
   this->_id = id;
   this->_name = name;
   this->_salary = salary;
   this->_managerId = managerId;
}

double Employee::getSalary() const
{
   return _salary;
}

Employee::~Employee()
{
}

string Employee::ToString()
{
   stringstream ss;

   ss <<fixed<< "ID: "<<setw(4)<<setfill(' ')<<this->_id<<" Name: "<<
           setw(10)<<this->_name+" Salary: "<<
           setw(10)<<setprecision(2)<<this->_salary<<" Manager ID: "<<
           setw(4)<<this->_managerId ;
   return ss.str();
}

void Employee::Raise(double raise)
{
   this->_salary += raise;
}

bool Employee::Equals(const Employee &anotherEmp)
{
   return (this->_id==anotherEmp._id);
}

bool Employee::Read(istream &in)
{
   return false;
}

void Employee::Write(ostream &out)
{

}

Employee.h


#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include <string>

typedef unsigned int uint;

using namespace std;


class Employee
{
private:
   uint _id;
   string _name;
   double _salary;
   uint _managerId;

public:
   Employee(uint, const string&, double, uint=0);
   Employee(const Employee &other);
   virtual ~Employee();
   uint getId() const;
   uint getManagerId() const;
   const string& getName() const;
   double getSalary() const;
   string ToString();
   void Raise(double);
   bool Equals(const Employee&);
   bool Read(istream &);
   void Write(ostream &);
};

#endif /* EMPLOYEE_H_ */

Company.cpp


#include "Company.h"
#include <sstream>
#include <iostream>
#include <iomanip>
using namespace std;
Company::Company()
{
   this->_head = NULL;
   this->_size = 0;
}

Company::~Company()
{
}

Company::Company(const Company &company)
{
   this->_head = company._head;
   this->_size = company._size;
}

bool Company::AddEmployee(const Employee &emp)
{
   Node * empNode = new Node, * currNode, *prevNode = NULL;
   // set employee data
   empNode->data = new Employee(emp);
   // set next node as null
   empNode->next = NULL;
   // set head node, if list is empty
   if(_head == NULL)
   {
       _head = empNode;
       _size = 1;
   }
   // else add to the end of list
   else
   {
       // start from head node
       currNode = _head;
       // when node in the list is not null
       while(currNode != NULL)
       {
           // No two IDs should be same
           // Insert at position where new empId is less than the next in list
           if(emp.getId() < currNode->data->getId())
           {
               // insert as head
               if(prevNode == NULL)
               {
                   // head as second in the list
                   empNode->next = _head;
                   // set new node as head node
                   _head = empNode;
               }
               else
               {
                   // set new node as next to previous
                   prevNode->next = empNode;
                   // set current node as next to new
                   empNode->next = currNode;
               }
               // increment employee count
               _size++;
               // return true
               return true;
           }
           // point current node to previous
           prevNode = currNode;
           // point next node in the list to current
           currNode = currNode->next;
       }
       // set empNode as last in list
       prevNode->next = empNode;
       // increment employee count
       _size++;
       // return true
       return true;
   }
   // adding employee to list failed
   return false;
}

bool Company::AddEmployee(uint id, const string &name, double salary,
       uint managerId)
{
   // create employee object
   Employee emp(id,name,salary,managerId);
   // call this class's overloaded AddEmployee function, and return status
   return AddEmployee(emp);
}

int Company::FindById(uint empid)
{
   // init pos value
   int pos = 0;
   // init current node as head
   Node * currNode = _head;
   while(currNode != NULL)
   {
       // increment position counter
       pos++;
       // if current nodes data matches empid
       if(currNode->data->getId() == empid)
       {
           // return pos value
           return pos;
       }
       // point to next node in list
       currNode = currNode->next;
   }
   // return not found indicator value
   return -1;
}

int Company::FindByIdBinarySearch(uint empid)
{
   // init pos value
   int start = 1, end = _size;
   int pivot;
   uint id;
   // init current node as head
   Employee * emp;
   while(start <= end)
   {
       // calculate pivot
       pivot = (start + end)/2;
       if(start > end)
       {
           break;
       }
       emp = Get(pivot);
       // get ID
       id = emp->getId();
       // if current nodes ID matches empid
       if(id == empid)
       {
           // return pos value
           return pivot;
       }
       else if(empid > id)
       {
           // set start as pivot + 1
           start = pivot + 1;
       }
       else
       {
           // set end as pivot -1
           end = pivot - 1;
       }
   }
   // return not found indicator value
   return -1;
}

int Company::FindByName(const string &name, uint startPos)
{
   // init pos value
   uint pos;
   // init current node as head
   Node * currNode = _head;
   // check if there are enough employees
   if(startPos <= _size && startPos > 0)
   {
       pos = 1;
       // move to startpos
       while(currNode != NULL && pos < startPos)
       {
           // skipping nodes till startpos
           currNode = currNode->next;
           // increament skip count
           pos++;

       }
       while(currNode != NULL)
       {
           // if current nodes data matches empid
           if(currNode->data->getName() == name)
           {
               // return pos
               return pos;
           }
           // increment position counter
           pos++;
           // point to next node in list
           currNode = currNode->next;
       }
   }
   // return not found pos value
   return -1;
}

int Company::Read(istream &in)
{
   uint empID, mID;
   string name;
   int count = 0;
   double salary;
   while(in >> empID)
   {
       in >> name >> salary >> mID;
       this->AddEmployee(empID,name,salary,mID);
       count++;
   }
   return count>0?count:-1;
}

int Company::Write(ostream &out)
{
   int count = 0;
   Node * empNode = _head;
   while(empNode!=NULL)
   {
       Employee *emp = empNode->data;
       // write employee data
       out<<emp->getId()<<" ";
       out<<emp->getName()<<" ";
       out<<fixed<<setprecision(2)<<emp->getSalary()<<" ";
       out<<emp->getManagerId()<<endl;
       // increment written count
       count++;
       // get next node in list
       empNode = empNode->next;
   }
   return count>0?count:-1;
}

bool Company::IsFull()
{
   return false;
}

Employee* Company::Get(uint pos)
{
   // init current node as head
   Node * currNode = NULL;
   uint currPos = 1;
   // check if there are enough employees
   if(pos <= _size && pos > 0)
   {
       currNode = _head;
       // move to startpos
       while(currNode != NULL && pos != currPos )
       {
           // skipping nodes till startpos
           currNode = currNode->next;
           // increment currPos counter
           currPos++;
       }
       // if node found
       if(currNode != NULL)
       {
           // return employee object
           return currNode->data;
       }
   }
   // if no such position in the list
   return NULL;
}

uint Company::GetEmployeeCount()
{
   // return employee count
   return _size;
}

Company.h

#ifndef COMPANY_H_
#define COMPANY_H_
#include "Employee.h"

class Company
{
private:
   struct Node{Employee *data;
   Node *next;
   };
   Node* _head;
   uint _size;
public:
   Company();
   virtual ~Company();
   Company(const Company &other);
   bool AddEmployee(const Employee&);
   bool AddEmployee(uint, const string &,double, uint=0);
   int FindById(uint);
   int FindByIdBinarySearch(uint);
   int FindByName(const string&, uint);
   int Read(istream &);
   int Write(ostream &);
   bool IsFull();
   Employee* Get(uint);
   uint GetEmployeeCount();

};

#endif /* COMPANY_H_ */

  

menu.cpp

#include <iostream>
#include <fstream>
#include "Company.h"
#include "Employee.h"

using namespace std;
void showMenu()
{
   cout<<endl;
   cout<<"1. Load from File"<<endl;
   cout<<"2. Save to File"<<endl;
   cout<<"3. List all Employees"<<endl;
   cout<<"4. Search by Name"<<endl;
   cout<<"5. Search by ID"<<endl;
   cout<<"6. Find Employee Boss Information"<<endl;
   cout<<"7. Add new Employee"<<endl;
   cout<<"8. Check if Database is Full"<<endl;
   cout<<"9. Exit"<<endl;
}

int main()
{
   int choice, pos;
   int recCount;
   unsigned int empId;
   bool isExit = false;
   unsigned int empCount;
   string fileName, nameToSearch;
   string name;
   double salary;
   unsigned int id, mId;
   ofstream out;
   ifstream in;
   Company company;
   do
   {
       // display menu;
       showMenu();
       // read user choice and take action
       // get user choice
       cout<<endl<<"Enter your choice: ";
       cin>>choice;
       switch(choice)
       {
           case 1:
               cout<<"Enter employee data file: ";
               cin >>fileName;
               // open file in read mode
               in.open(fileName,ios::in);
               if(in)
               {
                   recCount = company.Read(in);
                   if(recCount > 0)
                   {
                       cout<<recCount<<" employee records loaded."<<endl;
                   }
                   else
                   {
                       cout<<"No record found in file"<<endl;
                   }
               }
               else
               {
                   cout<<"Error reading file."<<endl;
               }
               // close stream
               in.close();
               break;
           case 2:
               cout<<"Where do you want to save the file: ";
               cin >>fileName;
               // open file in write mdoe
               out.open(fileName,ios::out);
               if(out)
               {
                   recCount = company.Write(out);
                   if(recCount > 0)
                   {
                       cout<<recCount<<" employee records written to "<<fileName<<endl;
                   }
               }
               else
               {
                   cout<<"Error writing file."<<endl;
               }
               // close stream
               out.close();
               break;
           case 3:
               empCount = company.GetEmployeeCount();
               cout<<"Empcout "<<empCount<<endl;
               // if employee count is 0
               if(empCount==0)
               {
                   cout<<"No employees are there in company."<<endl;
               }
               else
               {
                   // for each employee int the list
                   for(unsigned int i = 1; i <= empCount; i++)
                   {
                       // get employee at given position and print data on employee
                       cout << company.Get(i)->ToString()<<endl;
                   }
               }
               break;
           case 4:
               cout<<"Enter a name to search: ";
               cin>>nameToSearch;
               // start from position 1
               pos = 0;
               recCount = 0;
               do
               {
                   // get position of employee with given name from a given start position
                   pos = company.FindByName(nameToSearch,pos+1);
                   // if position is valid
                   if(pos > 0)
                   {
                       // get employee at given position and print data on employee
                       cout << company.Get(pos)->ToString()<<endl;
                       recCount++;
                   }
               }while(pos>0);
               if(recCount == 0)
               {
                   cout<<"No employee with name '"<<nameToSearch<<"' found in database."<<endl;
               }

               break;
           case 5:
               cout<<"Enter employee ID to search: ";
               cin>>empId;
               // find position of employee
               // sequential search
//               pos = company.FindById(empId);
               // binary search
               pos = company.FindByIdBinarySearch(empId);
               if(pos > 0)
               {
                   // get employee at given position and print data on employee
                   cout << company.Get(pos)->ToString()<<endl;
               }
               else
               {
                   cout<<"Sorry. No employee with ID - "<<empId<<" found."<<endl;
               }
               break;
           case 6:
               cout<<"Enter employee ID to find the boss: ";
               cin>>empId;
               // find position of employee
               pos = company.FindById(empId);
               if(pos > 0)
               {

                   Employee * emp;
                   // get employee at given position and print data on employee
                   emp = company.Get(pos);
                   cout << "Employee : "<< emp->ToString()<<endl;
                   // get Manager's position
                   pos = company.FindById(emp->getManagerId());
                   if(pos > 0)
                   {
                       // get manager at given position and print data on manager
                       cout <<"Manager : "<< company.Get(pos)->ToString()<<endl;
                   }
                   else
                   {
                       cout<<"Sorry. No manager with ID-"<<emp->getManagerId()<<" found."<<endl;
                   }
               }
               else
               {
                   cout<<"Sorry. No employee with ID-"<<empId<<" found."<<endl;
               }
               break;
           case 7:
               cout<<"Enter employee name: ";
               cin >>name;
               cout<<"Enter employee ID: ";
               cin >> id;
               cout<<"Enter employee salary: ";
               cin>> salary;
               cout<< "Enter Manager's ID: ";
               cin >> mId;
               if(company.AddEmployee(id,name,salary,mId))
               {
                   cout<<"Employee added to database."<<endl;
               }
               break;
           case 8:
               if(company.IsFull())
               {
                   cout<<"Datbase is full."<<endl;
               }
               else
               {
                   cout<<"Database is not full."<<endl;
               }
               break;
           case 9:
               isExit = true;
               break;
           default:
               cout<<"Invalid choice. Try again";
       }
   }while(!isExit);

   return 0;
}

Source Code Screenshots

Employee.h

Employee.cpp

Company.h

Company.cpp

menu.cpp

Output Screenshots


Related Solutions

Write a C program to run on unix to read a text file and print it...
Write a C program to run on unix to read a text file and print it to the display. It should count of the number of words in the file, find the number of occurrences of a substring, and take all the words in the string and sort them (ASCII order). You must use getopt to parse the command line. There is no user input while this program is running. Usage: mywords [-cs] [-f substring] filename • The -c flag...
Write a C++ program to read a data file containing the velocity of cars crossing an...
Write a C++ program to read a data file containing the velocity of cars crossing an intersection. Then determine the average velocity and the standard deviation of this data set. Use the concept of vector array to store the data and perform the calculations. Include a function called “Standard” to perform the standard deviation calculations and then return the value to the main function for printing. Data to use. 10,15,20,25,30,35,40,45,50,55. Please use something basic.
Write a C++ program to create a text file. Your file should contain the following text:...
Write a C++ program to create a text file. Your file should contain the following text: Batch files are text files created by programmer. The file is written in notepad. Creating a text file and writing to it by using fstream: to write to a file, you need to open thew file as write mode. To do so, include a header filr to your program. Create an object of type fsrteam. Open the file as write mode. Reading from a...
Part I The input to the program will be a text file containing the information for...
Part I The input to the program will be a text file containing the information for a tolerance table. An example follows using the values from the first lecture on tolerance analysis. These values will be stored in a text file. The data is comma delimited, which means that each data field is separated by a comma. If the first word is ‘PART’ the following values are the nominal size, +/- impact, tolerance, and fixed/variable. If the first word is...
Write a C++ program that does the following: Read and input file containing the following PersonAName,...
Write a C++ program that does the following: Read and input file containing the following PersonAName, PersonBName, XA,YA, XB, YB where the coordinates of PersonA in a 100 by 100 room is XA, YA and the coordinates of PersonB is XB, YB. Use square root function in cmath sqrt() to calculate the shortest distance between two points. A file will be uploaded in this assignment that will list coordinates of two people. The program should use a function call that...
Write a C++ program to open and read a text file and count each unique token...
Write a C++ program to open and read a text file and count each unique token (word) by creating a new data type, struct, and by managing a vector of struct objects, passing the vector into and out of a function. Declare a struct TokenFreq that consists of two data members: (1) string value; and (2) int freq; Obviously, an object of this struct will be used to store a specific token and its frequency. For example, the following object...
Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
(C++) Write a program to read from a grade database (data.txt). The database (text file) has...
(C++) Write a program to read from a grade database (data.txt). The database (text file) has students names, and grades for 10 quizzes.Use the given function prototypes to write the functions. Have main call your functions. The arrays should be declared in main() and passed to the functions as parameters. This is an exercise in parallel arrays, int and char 2 dim arrays. Function prototypes: int readData(ifstream &iFile, int scores[][10], char names[][30]); This functions takes the file stream parameter inFile...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT