如何将项目添加到输出文件?
How can I add items to the output file?
我是 C++ 的新手,我已经完成了第一份作业。我们有一个包含 5 个员工姓名、工资和工作时间的文本文件。
这是我的代码,以便我的程序可以读取它。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream input;
ofstream output;
string name;
int h;
float w;
int numEployee = 0;
double maxPay, minPay, avgPay;
int gross, adjGross;
//input/output file document path
input.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employees.txt");
output.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employeesoutput.txt");
//checks if the input file is working
if (input.fail())
{
cout << "Input file failed to open." << endl;
system("pause");
exit(0);
}
//checks if output file is working
if (output.fail())
{
cout << "Output file failed to open." << endl;
system("pause");
exit(0);
}
//prints the name, wage, hours worked of the employees to the output file
while (input >> name >> w >> h)
{
output << setw(5) << name << setw(5) << w << setw(5) << h << endl;
}
system("pause");
return 0;
}
它正在正确读取它并为我提供了我想要的输出文件,但缺少一些项目。完整的输出文件应包含员工人数、最高工资、最低工资、平均工资、总工资和调整后的总工资。
谁能帮我指出正确的方向?
谢谢
您要做的是在 while 循环语句(从文件中读取)中使用一些条件和语句。每次循环执行时增加 'numEmployee' 变量(计算条目数)。
比较 'w' 读取以检查它是否低于 minPay(初始化为非常大的值)然后更新 minPay 否则如果高于 maxPay(初始化为可能的最小值)更新 maxPay。
此外,将 'w' 添加到循环中的另一个变量 sumPay(初始化为零),最后将其除以 numEmployee 就完成了。
只需在 return 语句之前将它们输出到文件中。
我是 C++ 的新手,我已经完成了第一份作业。我们有一个包含 5 个员工姓名、工资和工作时间的文本文件。
这是我的代码,以便我的程序可以读取它。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream input;
ofstream output;
string name;
int h;
float w;
int numEployee = 0;
double maxPay, minPay, avgPay;
int gross, adjGross;
//input/output file document path
input.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employees.txt");
output.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employeesoutput.txt");
//checks if the input file is working
if (input.fail())
{
cout << "Input file failed to open." << endl;
system("pause");
exit(0);
}
//checks if output file is working
if (output.fail())
{
cout << "Output file failed to open." << endl;
system("pause");
exit(0);
}
//prints the name, wage, hours worked of the employees to the output file
while (input >> name >> w >> h)
{
output << setw(5) << name << setw(5) << w << setw(5) << h << endl;
}
system("pause");
return 0;
}
它正在正确读取它并为我提供了我想要的输出文件,但缺少一些项目。完整的输出文件应包含员工人数、最高工资、最低工资、平均工资、总工资和调整后的总工资。
谁能帮我指出正确的方向?
谢谢
您要做的是在 while 循环语句(从文件中读取)中使用一些条件和语句。每次循环执行时增加 'numEmployee' 变量(计算条目数)。
比较 'w' 读取以检查它是否低于 minPay(初始化为非常大的值)然后更新 minPay 否则如果高于 maxPay(初始化为可能的最小值)更新 maxPay。
此外,将 'w' 添加到循环中的另一个变量 sumPay(初始化为零),最后将其除以 numEmployee 就完成了。 只需在 return 语句之前将它们输出到文件中。