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

标签 c++ arrays writetofile

所以我这里有一些代码,它采用一个数组作为员工 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/

相关文章:

c++ - 如何将按键事件发送到 QWebElement?

c++ - 在 C++ 中如何将字符串数组转换为 float 数组?

javascript - 如何在angular js中将给定值附加到数组中

json 文件到 powershell 并返回到 json 文件

c++ - 如何解析要在 C++ 中阻止的文件

c++查找 vector 中元素的实际数量

ios - 在 Swift 2 中剪切数组元素

java - 克隆与在 Java 中复制数组?

ios - 写入应用程序支持目录

java - 使用多线程写入文本文件