编写程序利用动态数组存放n名学生的信息然后按照三门课程总分对学生进行降序排序并输出。学生人数n及每位学生信息已存放在文件stutxt中通过读取文件得到数据
假设文件stu.txt中每行为一个学生的信息,格式为“姓名 语文成绩 数学成绩 英语成绩”。
以下是一种可能的实现方式:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
int chinese;
int math;
int english;
int total;
};
bool compare(Student s1, Student s2) {
return s1.total > s2.total;
}
int main() {
ifstream fin("stu.txt");
int n;
fin >> n; // 读取学生人数
vector<Student> students(n);
for (int i = 0; i < n; i++) {
fin >> students[i].name >> students[i].chinese >> students[i].math >> students[i].english;
students[i].total = students[i].chinese + students[i].math + students[i].english;
}
fin.close();
sort(students.begin(), students.end(), compare);
for (int i = 0; i < n; i++) {
cout << students[i].name << " " << students[i].total << endl;
}
return 0;
}
解释:
- 打开文件stu.txt并读取学生人数n。
- 声明一个动态数组students,长度为n,存放学生信息。
- 用循环读取每个学生的信息,计算总分,并存入students数组中。
- 关闭文件stu.txt。
- 调用sort函数对students数组进行排序,排序规则由compare函数指定,即按照总分降序排序。
- 循环输出排序后的学生信息,包括姓名和总分
原文地址: https://www.cveoy.top/t/topic/hh2s 著作权归作者所有。请勿转载和采集!