有一个文件(“score.txt”)里面的数据格式如下:姓名 语文 数学 英语

要求读取文件里的数据,对每个同学的总分从高到低排序,最后输出学生姓名
C语言

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Student
{
public:
string name;
double sorce[4];
friend istream& operator>>(istream& is, Student& student)
{
is >> student.name >> student.sorce[0] >> student.sorce[1] >> student.sorce[2];
student.sorce[3] = student.sorce[0] + student.sorce[1] + student.sorce[2];
return is;
}
};
bool Greater(const Student& a, const Student& b)
{
return a.sorce[3] > b.sorce[3];
}
int main()
{
vector<Student> svec;
Student student;
ifstream infile("score.txt");
while(infile>>student)
svec.push_back(student);
sort(svec.begin(), svec.end(), Greater);
vector<Student>::const_iterator iter = svec.begin();
while(iter != svec.end())
cout<<"姓名:"<<(*iter++).name<<", 总分:"<<(*iter).sorce[3]<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜