我必须计算每个员工的工资。我该如何编写一个函数来执行此操作? 我如何根据工资对员工进行分类? 数据文件如下所示:我认为我必须将int转换为字符串或其他方式。我知道计算工资的功能是错误的。感谢。
A.Smith 20001 25 40
T.Philip 20002 20 35
S.Long 20003 15 50
G.Santos 20004 30 30
F.Farkas 20005 22 55
这是我想写的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdlib.h>
using namespace std;
struct Record
{
string name;
int id;
double rate;
int hrWorked;
double wage;
};
void read_file(string[], int);
void calculate_wage(Record& payroll);
int main()
{
int e = 5;
Record payroll[5];
string s[5];
cout << "Your entered file is: " << endl;
read_file(s, e);
calculate_wage(payroll);
system("pause");
return 0;
}
void read_file(string s[], int e)
{
ifstream myFile;
myFile.open("Project 3.dat");
string str;
int i = 0;
if (myFile.is_open())
{
while (getline(myFile, str))
{
s[i++] = str;
cout << str << endl;
}
myFile.close();
}
else
{
cout << "No Data Found!" << endl;
}
}
void calculate_wage (Record& payroll) // i know this part isnt right but im not sure what to do for this
{
char emplresult[256]; // need to convert int to string
payroll.wage = atoi(emplresult);
payroll.rate = atoi(emplresult);
payroll.hrWorked = atoi(emplresult);
for (int i = 0; i < 5; i++)
{
payroll[i].wage = payroll[i].rate * payroll[i].hrWorked;
}
}
答案 0 :(得分:0)
使用std算法,它将使您的代码可读和可维护。例如,您可以使用std::sort
对对象进行排序:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
struct Record
{
Record(std::string name, double wage) : name(name), wage(wage) {};
std::string name;
int id;
double rate;
int hrWorked;
double wage;
};
int main() {
using Records = std::vector<Record>;
Records records;
records.push_back(Record("Pedro",20));
records.push_back(Record("Andres",10));
records.push_back(Record("Santiago",15));
std::sort(records.begin(),records.end(),
[](auto& lhs, auto& rhs) {
return lhs.wage < rhs.wage;
});
for (const auto& r : records) {
std::cout << "Name: " << r.name << " wage: " << r.wage << "\n";
}
}
输出已排序的记录:
Name: Andres wage: 10
Name: Santiago wage: 15
Name: Pedro wage: 20
我希望这会为您的代码提供灵感!