源程序:
/*(文件注释头部开始)
*程序的版权和版本声明部分
*Copyright (c) 2011,烟台大学计算机学院学生
*All rights reserved.
*文件名称:文件的读取与保存
*作 者:2011级计114-3张宗佳
*完成日期:2012年6月6号
*版本号:vc
* 对任务及求解方法的描述部分
* 输入描术:
* 问题描述:
(1)定义学生类,其中包含姓名、C++课、高数和英语成绩及总分、均分数据成员,成员函数根据需要确定。
(2)读入这名学生的成绩,用对象数组进行存储。
(3)求出各科和总分的最高分。
(4)请按总分的降序(高成绩在前,低成绩在后)排序
(5)在屏幕上显示各科及总分的最高分,排序后的成绩单(包括总分)保存到文件odered_score.dat中。
* 程序输出:
* 程序头部的注释结束
*/
#include<fstream>
#include<iostream>
#include"string"
using namespace std;
class Student
{
public:
Student(){};
Student(string nam, double c, double m, double e):name(nam),cpp(c),math(m),english(e){total=c+m+e;}
void set_value(string nam, double c, double m, double e);
string get_name(){return name;}
double get_cpp(){return cpp;}
double get_math(){return math;}
double get_english(){return english;}
double get_total(){return total;}
void set_cpp(double c){cpp=c;}
void set_math(double m){math=m;}
void set_english(double e){english=e;}
void set_total(double t){total=t;}
private:
string name;
double cpp;
double math;
double english;
double total;
};
void Student::set_value(string nam, double c, double m, double e)
{
name=nam;
cpp=c;
math=m;
english=e;
total=c+m+e;
}
int main()
{
Student stu[100];
int i,j,t;
string sname;
double scpp,smath,senglish;
ifstream infile("score.dat",ios::in);//读入数据
if(! infile)//判断是否能打开文件
{
cerr << "open error!" << endl;
exit(1);
}
for(i = 0;i < 100; i++)
{
infile >> sname >> scpp >> smath >> senglish;//读入每个学生的信息
stu[i].set_value(sname,scpp,smath,senglish);
}
infile.close();//关闭文件
Student max_score("nobody",0,0,0);
for(i = 0;i < 100; i++)//各科最高分
{
if(stu[i].get_cpp() > max_score.get_cpp())
{
max_score.set_cpp(stu[i].get_cpp());
}
if(stu[i].get_math() > max_score.get_math())
{
max_score.set_math(stu[i].get_math());
}
if(stu[i].get_english() > max_score.get_english())
{
max_score.set_english(stu[i].get_english());
}
if(stu[i].get_total() > max_score.get_total())
{
max_score.set_total(stu[i].get_total());
}
}
//显示各科及总分的最高分
cout<<"C++最高分为: "<<max_score.get_cpp()<<endl;
cout<<"高等数学最高分为: "<<max_score.get_math()<<endl;
cout<<"英语最高分为: "<<max_score.get_english()<<endl;
cout<<"总分最高分为: "<<max_score.get_total()<<endl;
cout << "请到ordered_score.txt文件中查看保存的数据"<< endl;
ofstream outfile("ordered_score.txt",ios::out);//读出数据
if(!outfile)
{
cerr << "open error!" << endl;
exit(1);
}
for(j=0;j<100;j++) //总分排序
{
for(i=0;i<99-j;i++)
if (stu[i].get_total()<stu[i+1].get_total())
{
t=stu[i].get_total();
stu[i].set_total(stu[i+1].get_total());
stu[i+1].set_total(t);
}
}
//以文件形式保存数据
for(i=0;i<100;i++)
{
outfile<<stu[i].get_name()<<"\t";
outfile<<stu[i].get_cpp()<<"\t";
outfile<<stu[i].get_math()<<"\t";
outfile<<stu[i].get_english()<<"\t";
outfile<<stu[i].get_total()<<endl;
}
outfile.close();//关闭文件,防止数据丢失
system("pause");
return 0;
}
实验结果:
经验积累:
主要是对象数组的问题,设置一个set()函数用来设置每个学生的成绩
infile >> sname >> scpp >> smath >> senglish;//读入每个学生的信息
stu[i].set_value(sname,scpp,smath,senglish);