关于函数转化为类的问题。
例如:struct Employee{
string name;
int hour[8];
};
Employee workers[50];
我想在我的代码中使用类,代码如下,请问如何改动,可以和上面的例子不一样,只要转化就好。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
int in(int &num, int hour[][7], string name[]);
int * sum(int hour[][7], int num);
int * sort(int * total, int num);
void out(int num, int * tot, int * total,
string * name, int hour[][7]);
int main(){
int num;
int hour[50][7];
string name[50];
//step 1:judge success or failure of open file and input data of ont file
int file = in(num, hour, name);
if(file == 0)
return 0;
//step 2:calculate the sum of hours
int * total = sum(hour, num);
//step 3:sort from small to large
int * tot = sort(total, num);
//step 4:output data to another file
out(num, tot, total, name, hour);
return 0;
}
int in(int &num, int hour[][7], string name[]){
ifstream input;
input.open("empdata4.txt");
if(input.fail()){
cout << "input file error" << endl;
return 0;
}
input >> num;
for(int i = 0; i < num; i++){
input >> name[i];
for(int j = 0; j < 7; j++)
input >> hour[i][j];
}
input.close();
return 1;
}
int * sum(int hour[][7], int num){
int * total = new int[num];
for(int i = 0; i < num; i++){
total[i] = 0;
for(int j = 0; j < 7; j++)
total[i] += hour[i][j];
}
return total;
}
int * sort(int * total, int num){
int temp;
int * result = new int[num];
for(int i = 0; i < num; i++)
result[i] = total[i];
for(int i = 0; i < num - 1; i++)
for(int j = 0; j < num - 1; j++)
if(result[j] < result[j+1]){
temp = result[j];
result[j] = result[j+1];
result[j+1] = temp;
}
return result;
}
void out(int num, int * tot, int * total,
string * name, int hour[][7]){
ofstream output;
output.open("data4.txt");
output << "Employee Weekly Hours:" << endl << endl;
output << setw(20) << left << "Name:"
<< setw(3) << "S" << setw(3) << "M"
<< setw(3) << "T" << setw(3) << "W"
<< setw(3) << "T" << setw(3) << "F"
<< setw(3) << "S" << setw(3) << "TTL"
<< endl << endl;
for(int i = 0; i < num; i++)
for(int j = 0; j < num; j++)
if(tot[i] == total[j]){
output << setw(18) << left << name[j] << " ";
for(int k = 0; k < 7; k++)
output << setw(2) << right << hour[j][k] << " " ;
output << setw(4) << tot[i] << endl;
total[j] = -1;
break;
}
output.close();
}