write C++ programs
Array of Payroll Objects
Design a PayRoll class that has data members for an employee’s
hourly pay rate and
number of hours worked. Write a program with an array of seven
PayRoll objects. The
program should read the number of hours each employee worked and
their hourly pay
rate from a file and call class functions to store this information
in the appropriate
objects. It should then call a class function, once for each
object, to return the employee’s
gross pay, so this information can be displayed. Sample data to
test this program can be
found in the payroll.dat file.
To create the payroll.dat file, please open notepad, copy/paste the following data and save the file as payroll.dat file. Please make sure to save the file in a place where your program file is located. In otherwords, please do not hard code the path for the payroll.dat .
40.0 10.00
38.5 9.50
16.0 7.50
22.5 9.50
40.0 8.00
38.0 8.00
40.0 9.00
sample output.
Employee 1: 400.00
Employee 2: 365.75
Employee 3: 120.00
Employee 4: 213.75
Employee 5: 320.00
Employee 6: 304.00
Employee 7: 360.00
Answer code with explanation in comments:
#include <iostream>
using namespace std;
// Payroll class
class Payroll {
public:
// Instance variables.
double hourlyPayRate;
double hoursWorked;
// Constructor.
Payroll(double hourlyPayRate, double hoursWorked)
{
this->hourlyPayRate = hourlyPayRate;
this->hoursWorked = hoursWorked;
}
// getGrossPay() method to return Gross Pay of the Employee.
double getGrossPay()
{
return (this->hourlyPayRate)*(this->hoursWorked);
}
// Empty Constructor.
Payroll()
{}
};
// main function.
int main()
{
// variables to read from the file.
char hourlyPayRate[100];
char hoursWorked[100];
// Declaring 7 Payroll objects.
Payroll* payroll = new Payroll[7];
// Opening the file in read mode.
FILE* ptr = fopen("payroll.dat","r");
int i=0;
// Reading the file line by line and initializing each payroll
object.
while (fscanf(ptr, "%s %s", hourlyPayRate, hoursWorked)==2)
{
payroll[i] = Payroll(stod(hourlyPayRate), stod(hoursWorked));
i++;
}
// Printing the gross pay for each Employee in format as
required.
for(int i=0; i<7; i++)
printf("Employee %d: %0.2lf\n", i+1,
payroll[i].getGrossPay());
return 0;
}
Screenshots:
Get Answers For Free
Most questions answered within 1 hours.