gpt4 book ai didi

c++ - 如何让数组显示在文件中?

转载 作者:行者123 更新时间:2023-11-30 05:40:07 25 4
gpt4 key购买 nike

所以我这里有一些代码,它采用一个数组作为员工 ID,然后还填充工作时间、工资率等数组,然后将它们全部显示出来。这部分没有问题,一切运行顺利。但是,我试图将此数据写入文件,但不是将所有员工的数据写入文件,而是只写入一名员工的数据。我似乎无法弄清楚为什么!

    #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;
}

最佳答案

您将在写入第一条记录后关闭文件。

改变:

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

收件人:

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

关于c++ - 如何让数组显示在文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com