2

我正在为学校编写一个 C++ 程序,它正在出现,但我在这个特定领域遇到了麻烦。

我需要从另一个函数的循环中调用一个函数。我需要读取 5 行并将读取的每个数字集合放入一个双精度值。现在我只是想确保我可以正确读取文件。目前,每当我运行程序时,它都会循环并打印五次信息,但似乎只打印最后一行的数字五次。

我的代码中的什么使得我的程序只适用于我的输入文件的最后一行?

这是我的信息:

需要读取的输入文件:

1121 15.12 40                                                                                     

9876 9.50 47

3333 22.00 35

2121 5.45 43

9999 10.00 25

我正在使用的代码:

 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;
     }
}
4

3 回答 3

2

while (!employeeInputFile.eof())意味着它将一直读取行直到文件结束。每次执行主体时,它都会覆盖最后读取的值。

当后续process_payroll调用时process_employee,它会重新打开流并再次执行相同的操作,因此相同的值会打印 5 次。

于 2012-11-05T01:49:21.093 回答
2

从省略下面的 while 循环开始:

 //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;
 }

然后你会注意到你只得到第一行输入。您应该考虑将输入流传递给process_employee.

于 2012-11-05T01:50:42.817 回答
2

你不断覆盖你的变量:

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));
}

然后,传递该向量并打印信息。

于 2012-11-05T01:54:34.413 回答