Reputation: 47
I made a program to calculate the total pay for 7 employees. The program read from a file (payroll.dat), to get data for data members "hours" and "payrate". The output for all 7 emplyeress is 0.00, datafile >> hours; datafile >> payrate; seems correct. I am not sure why why the program is not reading from the file and inputting the data into the members.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
class Payroll
{
private:
double hours;
double payrate;
double grosspay;
public:
Payroll()
{
hours = 0.0;
payrate = 0.0;
grosspay = 0.0;
}
Payroll(double h, double p)
{
hours = h;
payrate = p;
grosspay = hours * payrate;
}
double setHours(double h)
{
hours = h;
}
double setPayrate(double p)
{
payrate = p;
}
double getHours()
{
return hours;
}
double getPayrate()
{
return payrate;
}
double getGrosspay()
{
return grosspay;
}
};
const int employees = 7;
int main()
{
double hours;
double payrate;
double grosspay;
int index;
Payroll totalPay[employees];
{
ifstream datafile;
datafile.open("payroll.dat");
if (!datafile)
cout << "Error opening data file \n";
else
{
for (index = 0; index < 7; index++)
{
datafile >> hours;
datafile >> payrate;
grosspay = hours * payrate;
cout << endl;
cout << fixed << setprecision(2);
cout << "Employee" << (index + 1) << ": " << totalPay[employees].getGrosspay() << endl;
}
}
datafile.close();
}
return 0;
}
Upvotes: 0
Views: 61
Reputation: 60208
In your innermost for
loop, you are doing:
grosspay = hours * payrate;
but the variable grosspay
is just a local variable, and does not update the totalPay
array. So this line:
cout << "Employee" << (index + 1) << ": " << totalPay[employees].getGrosspay() << endl;
prints the grosspay
of a default constructed Payroll
.
Instead of assigning to a local variable, you need to do something like:
totalPay[index] = Payroll(hours, payrate);
which constructs a correct Payroll
object and assigns it to an index in the array.
Upvotes: 1