fmarie14
fmarie14

Reputation: 21

How to get arrays to show up on a file?

So I have some code here that takes an array for employee id and then also fills arrays for hours worked, pay rate, etc and then displays them all. There is no trouble with this part and it all runs smoothly. However I am trying to write this data to a file, but instead of writing the data for all the employees to the file it only writes the data for one employee. I cant seem to figure out why!

    #include <iostream>
    #include <iomanip>
    #include <fstream>

    using namespace std;
    int main()
    {
    ofstream outputFile;
    const int numOfEmployees = 7;
    int long empId[numOfEmployees] = { 5658845, 4520125, 7895122, 8777541,                    8451277, 1302850, 7580489 };  
    int hours[numOfEmployees];
    double payRate[numOfEmployees];
    double wages[numOfEmployees];

    outputFile.open("PayrollDataBackup.txt");

    cout << "Enter the hours worked by 7 employees and their hourly pay        rates."<<endl;
    cout << " " << endl;
    for (int count = 0; count < numOfEmployees; count++)
    {
    cout << "Hours worked by employee #" << empId[count] << ":";
    cin >> hours[count];
    while (hours < 0)
    {
        cout << "Please enter a positive number: ";
        cin >> hours[count];
    }
    cout << "Hourly pay rate for employee #" << empId[count] << ":";
    cin >> payRate[count];
    while (payRate[count] < 15.00)
    {
        cout << "Please enter a pay rate higher than $6.00: ";
        cin >> payRate[count];
    }
}
cout << " " << endl;
cout << "Here are the hours worked, pay rate and gross pay for each employee:" << endl;
cout << " " << endl;

for (int count = 0; count < numOfEmployees; count++)
{
    wages[count] = hours[count] * payRate[count];

    cout << " " << endl;
    cout << fixed << showpoint << setprecision(2);
    cout <<"ID:"<< empId[count] <<" Hours: "<< hours[count] << " Pay rate: $" << payRate[count] <<" Wage: $" << wages[count] << endl;

}
for (int count = 0; count < numOfEmployees; count++)
{

    outputFile << empId[count] << " " << hours[count] << " " << payRate[count] << " " << endl;
    outputFile.close();
}

system("pause");
return 0;
}

Upvotes: 1

Views: 38

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63755

You are closing the file after writing the first record.

Change:

for (int count = 0; count < numOfEmployees; count++)
{
    outputFile << empId[count] << " " << hours[count] << " " << payRate[count] << " " << endl;
    outputFile.close();
}

To:

for (int count = 0; count < numOfEmployees; count++)
{
    outputFile << empId[count] << " " << hours[count] << " " << payRate[count] << " " << endl;
}
outputFile.close();

Upvotes: 1

Related Questions