假设文件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;
}

解释:

  1. 打开文件stu.txt并读取学生人数n。
  2. 声明一个动态数组students,长度为n,存放学生信息。
  3. 用循环读取每个学生的信息,计算总分,并存入students数组中。
  4. 关闭文件stu.txt。
  5. 调用sort函数对students数组进行排序,排序规则由compare函数指定,即按照总分降序排序。
  6. 循环输出排序后的学生信息,包括姓名和总分

原文地址: https://www.cveoy.top/t/topic/hh2s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录