这是我的代码:
#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;
}
}
我不确定这有什么问题。如果有人能指出我正确的方向并解释什么是错的或者我能改进什么,那会爱吗?
谢谢!
答案 0 :(得分:0)
您在您的函数DetermineSalary中声明了工资变量。每个函数调用,数据都存储在函数内部的变量中,而不是main中声明的工资变量。删除函数内的工资变量,它应该可以工作。
答案 1 :(得分:0)
我重写了你的代码。请在下面的代码中查看您的错误。试试这个,如果您需要更多帮助,请告诉我。
//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);
}