我正在用 C++ 为学校编写一个程序,它正在运行,但我在这个特定领域遇到了麻烦。
我需要从另一个函数的循环中调用一个函数。我需要读取 5 行并将读取的每个数字集合放入一个 double 值中。现在我只是想确保我可以正确阅读文件。目前,每当我运行该程序时,它都会经历循环并打印信息五次,但它似乎只打印最后一行的数字五次。
我的代码中有什么使得我的程序只适用于输入文件的最后一行?
这是我的信息:
需要读取的输入文件:
1121 15.12 40 9876 9.50 47 3333 22.00 35 2121 5.45 43 9999 10.00 25
Code that I'm working with:
double process_employee(double& employeeNumber, double& employeeRate, double& employeeHours)
{
ifstream employeeInputFile;
employeeInputFile.open("employee input file.txt");
if(employeeInputFile.fail())
{
cout << "Sorry, file could not be opened..." << endl;
system("pause");
exit(1);
}
//For some reason, this is only printing the data from the last line of my file 5 times
while (!employeeInputFile.eof())
{
employeeInputFile >> employeeNumber >> employeeRate >> employeeHours;
}
}
void process_payroll()
{
double employeeNumber = 1.0;
double employeeRate = 1.0;
double employeeHours = 1.0;
cout << "Employee Payroll" << endl << endl;
cout << "Employee Hours Rate Gross Net Fed State Soc Sec"
<< endl;
//caling process_employee 5 times because there are 5 lines in my input file
for(int i = 1; i <= 5; i++)
{
process_employee(employeeNumber, employeeRate, employeeHours);
cout << "Employee #: " << employeeNumber << " Rate: " << employeeRate << " Hours: "
<< employeeHours << endl;
}
}
最佳答案
你不断地覆盖你的变量:
while (!employeeInputFile.eof())
{
employeeInputFile >> employeeNumber >> employeeRate >> employeeHours;
}
您需要将它们保存在中间,例如:
std::vector<EmployeeStructure> someVector;
while (!employeeInputFile.eof())
{
employeeInputFile >> employeeNumber >> employeeRate >> employeeHours;
someVector.push_back(EmpoyeeStructure(employeeNumber, employeeRate, employeeHours));
}
然后,传递该 Vector 并打印信息。
关于c++ - 从文件中读取行并将它们放入变量中时遇到问题 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13224936/