使用函数和数组写入两个文件

时间:2013-04-26 22:56:34

标签: c++ arrays file function

我尝试了所有东西,我所拥有的东西是我知道的不正确但至少输出格式化我需要它为两个文件之一。我需要将信息发送到两个单独的.txt文件中,这两个文件都带有不同的信息。如何使用我已有的当前数组函数执行此操作。我花了好几个小时试图解决这个问题,现在它取决于你们所有人!谢谢。

主 -

#include<iostream>
#include<fstream>
#include<string>
#include "Payroll.h"
using namespace std;


const int NUM_EMPLOYEE = 75;

int main()
{
    int dependents;
    double payrate;
    string name;
    double hours;
    ifstream fin;
    int count = 0;
    Payroll employeeArray[NUM_EMPLOYEE];

    fin.open("employeeData.txt");

    if (!fin)
    {
        cout << "Error opening data file\n";
        return 0;
    }
    else
    {
        while(fin >> payrate >> dependents)
        {
            getline(fin, name);
            employeeArray[count].setWage(payrate);
            employeeArray[count].setDependents(dependents);
            employeeArray[count].setName(name);
            cout << "How many hours has" << name << " worked? ";
                cin >> hours;
                employeeArray[count].setHours(hours);
            count++;
        }

    }

    for (int i = 0; i < count; i++)
    {
        employeeArray[i].printPayDetails(cout << endl);
    }

    cout << endl;

    return 0;
}

打印功能 -

void Payroll::printPayDetails(ostream& out)
{
    double normPay = getNormPay();
    double overTime = getOverPay();
    double grossPay = getGrossPay();
    double taxAmount = getTaxRate();
    double netPay = computePay();
    const int SIZE = 9;
    out << fixed << setprecision(2) << right << setw(5) << hours  << setw(SIZE)  << normPay << setw(SIZE) << overTime ;
    out << setw(SIZE) << grossPay << setw(SIZE) << taxAmount <<setw(SIZE) << netPay;
}

1 个答案:

答案 0 :(得分:2)

你的问题措辞有点不稳定,但我想我得到你所说的。如果要输出到两个不同的文件,则需要两个字符串流。以下是一个例子:

#include <fstream>

void main()
{
     //Open file 1
     ofstream file1;
     file1.open("file1.txt");
     file1 << "Writing stuff to file 1!";

     //Open file 2
     ofstream file2;
     file2.open("file2.txt");
     file2 << "Writing stuff to file 2!";

     //That the files are open you can pass them as arguments to the rest of your functions.
     //Remember to use &


     //At the end of your program remember to close the files
     file1.close();
     file2.close();
}