C++ 实现学生成绩排名
创建一个 学生(student)类,包含学号、姓名、语文、数学、英语成绩。
输入格式
1.从TXT文件中读取以有的学生信息。
TXT 的文件组织如下,使用逗号 , 分割。
学号,姓名,语文成绩,数学成绩,英语成绩
202201011,李青,98,100,58
202301001,张伟,85,92,78
202301002,李娜,90,88,95
202301003,王强,78,84,80
202301004,赵敏,88,91,84
202301005,刘洋,82,79,89
202301006,陈静,94,87,92
202301007,杨涛,76,81,77
202301008,孙丽,89,90,88
202301009,周明,81,85,90
202301010,吴艳,77,80,82
输出格式
按总成绩从高到低排序。
1 202301002 李娜 90 88 95 273
2 202301006 陈静 94 87 92 273
3 202301008 孙丽 89 90 88 267
4 202301004 赵敏 88 91 84 263
5 202201011 李青 98 100 58 256
6 202301009 周明 81 85 90 256
7 202301001 张伟 85 92 78 255
8 202301005 刘洋 82 79 89 250
9 202301003 王强 78 84 80 242
10 202301010 吴艳 77 80 82 239
11 202301007 杨涛 76 81 77 234
实现代码
#include<iostream>
#include<vector>
#include<algorithm>
#include <fstream> // 读取txt文件用到的库
#include <sstream>
using namespace std;
class Student
{
private:
string studentID;
string name;
double chinese;
double math;
double english;
double totalScore;
public:
// 无参的构造函数
Student() :studentID(""), name(""), chinese(0), math(0), english(0), totalScore(0) {};
// 有参构造函数
Student(const string& id, const string& n, double chinese, double math, double english)
:studentID(id), name(n), chinese(chinese), math(math), english(english)
{
totalScore = chinese + math + english; // 计算总成绩
}
void setID(const string& id)
{
studentID = id;
}
void setName(const string& n)
{
name = n;
}
void setScore(double chinese, double math, double english)
{
this->chinese = chinese; // 设置成员变量,参数名和变量名相同要用this 指针
this->math = math;
this->english = english;
this->totalScore = chinese + math + english;
}
string getID() const
{
return studentID;
}
string getName()const
{
return name;
}
double getChinese()const
{
return chinese;
}
double getMath()const
{
return math;
}
double getEnglish()const
{
return english;
}
double getTotalScore()const
{
return totalScore;
}
~Student() {};
};
int main()
{
ifstream file("student.txt");
vector<Student> students; // vector 容器创建student
string line;
if (!file.is_open())
{
cerr << "无法打开文件" << endl;
return 1;
}
getline(file, line); // 空过第一行
while (getline(file, line))
{
stringstream ss(line);
string id, name;
double chinese, math, english;
//读取数据
getline(ss, id, ',');
getline(ss, name, ',');
ss >> chinese;
ss.ignore();
ss >> math;
ss.ignore();
ss >> english;
//创建学生对象 并添加到向量中
students.push_back(Student(id, name, chinese, math, english));
}
file.close();
// 按总成绩排序
// sort 方法(迭代器起始位置,迭代器尾部后一个位置,表达式)
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.getTotalScore() > b.getTotalScore();
});
//输出排序后的结果
for (size_t i = 0; i < students.size(); ++i)
{
cout << i + 1 << " " << students[i].getID() << " " << students[i].getName() << " " <<
students[i].getChinese() << " " << students[i].getMath() << " " << students[i].getEnglish() <<
" " << students[i].getTotalScore() << endl;
}
return 0;
}
缺点和进一步改进
使用vector 容器和sort排序方法,没有自己实现具体存储和排序算法。