无法从文件中读取行并将它们放入变量(C ++)

时间:2012-11-05 01:45:35

标签: c++ file function io

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

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

我的代码中有什么内容使我的程序只能使用输入文件的最后一行?

这是我的信息:

需要阅读的输入文件:

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

3 个答案:

答案 0 :(得分:2)

while (!employeeInputFile.eof())表示它将继续读取行直到文件结尾。每次执行主体时,它都会覆盖最后读取的值。

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

答案 1 :(得分: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

答案 2 :(得分: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));
}

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