【发布时间】:2013-04-21 05:10:07
【问题描述】:
我尝试了所有方法,但我知道我所拥有的是不正确的,但至少输出的格式是我对两个文件之一的需要。我需要将信息发送到两个单独的 .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;
}
【问题讨论】:
-
你想达到什么结果?你还没有真正问过一个具体的问题。还有,这是作业吗?
-
如果您询问如何将输出写入不同的文件,请尝试谷歌搜索“c++ 文件流”
-
您当前正在打印到标准输出。您不会将其发送到 2 个不同的文件。你设法让
ifstream工作,所以ofstream应该不会太难。 -
我想调用 main 中的 print 函数来写入我的两个文件。当我这样做时,循环不起作用,它们只发送 .txt 输入文件中的最后一行信息。我可以在函数中打开和关闭两个.txt输出文件吗?
-
当您尝试新事物时,请单独尝试,不要将其移植到一个大型预先存在的程序中。尝试编写最短、最简单的程序,将两个不同的单词写入两个不同的文件。如果它有效,那么你可以将它集成到其他东西中;如果没有,它会更容易修补。