从数组和函数向两个文件发送输出
Sending OutPut to two files from an array and a function
我哪里做错了?当我发送这个时,我得到的是完全空白的文件?我需要重新工作数组还是函数实际上没有发送任何东西到文件?这是家庭作业,所以有帮助的建议会很好。我很困惑,所以非常需要帮助。
Main- #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];
ofstream fout;
fin.open("employeeData.txt");
if (!fin)
{
cout << "Error opening data filen";
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++;
}
}
fout.open("payrollDetails.txt");
fout << " Name Hours Regular Overtime Gross Taxes Net" << endl; // heading for file
fout.close();
fout.open("checkInfo.txt");
fout << "Net Pay Name"; // heading for file two
fout.close();
for (int i = 0; i < count; i++)
{
employeeArray[i].printPayDetails(fout << 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;
ofstream fout;
fout.open("payrollDetails.txt");
out << setw(19) << left << name << fixed << setprecision(2) << right << setw(5) << hours << setw(SIZE) << normPay << setw(SIZE) << overTime ;
out << setw(SIZE) << grossPay << setw(SIZE) << taxAmount <<setw(SIZE) << netPay;
fout.close();
fout.open("checkInfo.txt");
out << netPay << " " << name;
fout.close();
}
我看到的唯一问题是您没有清除流中的前导换行符:
while (fin >> payrate >> dependents)
{
getline(fin, name);
在while循环中执行提取后,在流中留下一个换行符。std::getline()
将在看到换行符时停止输入,因此您必须通过调用ignore()
:
fin.ignore();
getline(fin, name);
由于ignore()
返回对流的引用,您甚至可以在形参中使用它:
getline(fin.ignore(), name);
但是更习惯的是使用std::ws
,一个放弃所有前导空格的操纵符:
getline(fin >> ws, name);
您还需要将它放在if
语句中以检查它是否成功:
while (fin >> payrate >> dependents && getline(fin >> ws, name))
{
// ...
相关文章:
- 两个文件使用彼此的功能-如何解决
- 结构包含在两个头文件中,这两个文件我都不拥有
- Levenshtein 两个文件的距离花费了太多时间
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 包括两个文件 C++ 之间的冲突
- 如何检测两个文件条目是否引用与Qt相同的物理文件系统?
- 比较两个文件夹的关系
- 连接两个文件时如何避免冗余尾随换行符?
- 在循环工作时,首先将两个文件读为向量,但仅次于迭代一次
- 比较两个文件中的两个中间人的最佳方法.C++
- 同时逐行阅读两个文件
- 包含两个C++文件的制作文件:如何选择要编译的文件
- 在 c++ 中对两个文件使用标头
- 同时阅读两个文件
- 如何连接两个文件夹/项目的生成文件,这两个文件夹/项目必须一起运行且独立运行
- 从其他两个文件中创建一个分类整数的文件
- C 程序处理两个文件,而不是一个文件
- 知道分割故障在哪里比较两个文件
- 如何计算两个文件中字符单词和行的总数,并将它们相加以得出总数
- 将相同数据写入两个文件的有效方法