C 功能:读取直到文件结束 - 查找代码中的错误
C++ Functions: Reading until End of File- Finding error in code
- 编写一个程序,该程序使用循环读取文件并读取直到线结束。
- 写一个值返回的功能,该功能将工资计算为工作时间小时费率
- 文件input.txt包含:姓氏,工作时间,小时费率。
- 例如:史密斯80 15.00
- 打开文件并检查文件状态,如果文件未打开,则退出程序。
- 在循环中读取数据并调用该功能以计算工资
- 函数呼叫输出计算的工资后。
这是我的代码:
#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);
}
相关文章:
- Printf 命令不打印时添加了查找常见除数的新代码
- 如何使用 lldb 查找我的代码运行的位置
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 在代码块中查找输出文件
- 旧C++代码中的目录查找导致 OS X Catalina 10.15 中的目录错误
- 用于查找最低共同祖先的代码不适用于某些测试用例
- 查找在 4 和问题中代码失败的测试用例
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 如何查找导致结果不一致的代码
- 用于查找连续子数组的最大总和的代码使测试用例失败
- 我正在努力在随机数组中查找最小值,有人知道为什么我的代码不起作用?C++
- 我的代码似乎在查找最大数字时存在语法错误
- 在编写代码以查找数组中的对数时获取分段错误
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 通过查找一对项目的代码获取错误的输出,在给定的总和相等的给定列表中列表
- 在C++代码中查找编号函数
- C 功能:读取直到文件结束 - 查找代码中的错误
- 是否可以使用内联汇编在 Visual Studio 2010 c++ 中查找代码的地址?
- 查找代码中的逻辑缺陷或低效率
- 调试__do_global_dtors_aux以查找代码位置