- void set_salarys( ):输入职工工资(输入-1标志着工资输入结束),工资保存到salary数组中,实际人数保存到number中;
- void add_salarys(int x):给每个人涨x元工资
- void sort_salarys():对工资排序
- void show_salarys( ):显示工资信息
(2)用salary[50]有限制,实际人数少时,会浪费空间,人数多了,无法完成任务。在main()中先输入职工人数,作为参数传递给输入职工工资的成员函数,然后利用动态分配内存的机制,开辟一个大小正好的连续空间,完成上面的工作。
(3)手工输入工资?!太让人不能忍受了。现给出包含了不足500个职工工资的文件salary.txt( 点击打开链接 ),从文件中读数据,完成上面的工作。
(4)增加一个成员函数,将排序后结果保存到一个文件中。
(5)用多文件的方式组织最后的程序。
这里直接展示第二步的代码:
/*
*copyright (c) 2015,
*All rights reserved
*The Author:王争取¡
*Finished Time:2015.3.25
*/
#include <iostream>
using namespace std;
class Salary
{
public:
void set_salary();
void sort_salary();
void add_salary();
void show_salary();
private:
double *salary;
int num;
};
void Salary::set_salary()
{
int x;
cout<<"set the number of people"<<endl;
cin>>num;
salary=new double[num];
cout<<"please set salary"<<endl;
for(int i=0; i<num; i++)
{
cin>>x;
salary[i]=x;
}
}
void Salary::add_salary()
{
int x;
cout<<"please add the salary for them"<<endl;
cin>>x;
for(int i=0; i<num; i++)
salary[i]+=x;
}
void Salary::sort_salary()
{
int x;
for (int i=0; i<num-1; i++)
for(int j=0; j+i<num; j++)
{
if(salary[i]<salary[j])
{
x=salary[j];
salary[j]=salary[i];
salary[i]=x;
}
}
}
void Salary::show_salary()
{
cout<<"sort salary frome high to low"<<endl;
for(int i=0; i<num; i++)
cout<<salary[i]<<" ";
}
int main()
{
Salary salary;
salary.set_salary();
salary.add_salary();
salary.sort_salary();
salary.show_salary();
return 0;
}
第四个问题代码如下:
/*
*copyright (c) 2015,
*All rights reserved
*The Author:王争取¡
*Finished Time:2015.3.25
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int N=500;
class Salary
{
public:
void set_salary();
void sort_salary();
void add_salary();
void show_salary();
void write_data() ;
private:
double salary[N];
int num;
};
void Salary::set_salary()
{
int i=0;
ifstream infile("salary.txt",ios::in);
if(!infile)
{
cout<<"open error"<<endl;
exit(1);
}
while(infile>>salary[i])
i++;
num=i;
infile.close();
}
void Salary::add_salary()
{
int x;
cout<<"please add the salary for them"<<endl;
cin>>x;
for(int i=0; i<num; i++)
salary[i]+=x;
}
void Salary::sort_salary()
{
int x;
for (int i=0; i<num-1; i++)
for(int j=0; j+i<num; j++)
{
if(salary[i]<salary[j])
{
x=salary[j];
salary[j]=salary[i];
salary[i]=x;
}
}
}
void Salary::show_salary()
{
cout<<"sort salary frome high to low"<<endl;
for(int i=0; i<num; i++)
cout<<salary[i]<<" ";
}
void Salary::write_data( )
{
int i;
ofstream outfile("salary_ordered.txt",ios::out);
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0; i<num; ++i)
{
outfile<<salary[i]<<endl;
}
outfile.close();
}
int main()
{
Salary salary;
salary.set_salary();
salary.add_salary();
salary.sort_salary();
salary.write_data();
salary.show_salary();
return 0;
}
第三个问题中用到了开辟空间和对文件的打开与保存,这些应熟练掌握