C 功能:读取直到文件结束 - 查找代码中的错误

C++ Functions: Reading until End of File- Finding error in code

本文关键字:查找 代码 错误 结束 文件 功能 读取      更新时间:2023-10-16
  1. 编写一个程序,该程序使用循环读取文件并读取直到线结束。
  2. 写一个值返回的功能,该功能将工资计算为工作时间小时费率
    • 文件input.txt包含:姓氏,工作时间,小时费率。
    • 例如:史密斯80 15.00
  3. 打开文件并检查文件状态,如果文件未打开,则退出程序。
  4. 在循环中读取数据并调用该功能以计算工资
  5. 函数呼叫输出计算的工资后。

这是我的代码:

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    float DetermineSalary(ifstream& inFile, float hoursWorked, float 
    hourlyRate);
    int main (){
        ifstream inFile;
        inFile.open("input.txt");//opening file
        string name;
        float hoursWorked, hourlyRate;
        float salary;
        inFile >> name >> hoursWorked >> hourlyRate; //priming read
     while(inFile){
         inFile >> name >> hoursWorked >> hourlyRate;
         DetermineSalary(inFile, hoursWorked, hourlyRate);
         cout << "The salary for " << name << "is: $"  << salary << endl;
     }
    if (!inFile){
         cout << "Error opening file." << endl;
         return 1;
     }
  }
float DetermineSalary(ifstream& inFile, float hoursWorked, float hourlyRate){
    string name;
    float salary;
     getline(inFile, hoursWorked);
     getline(inFile, hourlyRate);
     getline(inFile, name);
     while(inFile){
         salary = hoursWorked * hourlyRate;
     }
}

我不确定这是怎么回事。如果有人可以将我指向正确的方向并解释我可以改善什么是什么?

谢谢!

您在函数内声明了薪金变量决定性。每个函数调用,数据都存储在可变内部功能中,而不是在MAIN中声明的工资变量。删除工资变量内部功能,它应该可以工作。

我已经重写了您的代码。请在下面的代码中查看您的错误。尝试一下,让我知道您是否需要更多帮助。

//using namespace std;
float DetermineSalary( float hoursWorked, float  hourlyRate);
int main (){
    std::ifstream inFile;
    inFile.open("input.txt");//opening file
    if (!inFile){
         std::cout << "Error opening file." << std::endl;
         return 1;
    }
    std::string name;
    std::string hW, hR;
    float hoursWorked = 0, hourlyRate = 0;
    float salary;
    //inFile >> name >> hoursWorked >> hourlyRate; //priming read you dont need this line
    while(inFile >> name >> hW >> hR){
       hoursWorked = ::atof(hW.c_str());
       hourlyRate = ::atof(hR.c_str());
       salary = DetermineSalary(hoursWorked, hourlyRate);
       std::cout << "The salary for " << name << "is: $"  << salary << std::endl;
    }
}
float DetermineSalary(float hoursWorked, float hourlyRate){
  return (hoursWorked + hourlyRate);
}