结构体输出 总分最高的学生的姓名及总分,并将结果保存在out.txt中

学生的基本信息包括学号、姓名及总分。从in.txt中读取5名学生的基本信息,输出 总分最高的学生的姓名及总分,并将结果保存在out.txt中

基于new bing的编写:


#include <stdio.h>
#include <string.h>

struct student {
    int id;
    char name[20];
    int total_score;
};

int main() {
    FILE *fp_in, *fp_out;
    struct student stu[5];
    int max_index = 0;

    // 打开输入文件
    fp_in = fopen("in.txt", "r");
    if (fp_in == NULL) {
        printf("Open input file failed!\n");
        return 1;
    }

    // 读取学生信息
    for (int i = 0; i < 5; i++) {
        fscanf(fp_in, "%d %s %d", &stu[i].id, stu[i].name, &stu[i].total_score);
        if (stu[i].total_score > stu[max_index].total_score) {
            max_index = i;
        }
    }

    // 关闭输入文件
    fclose(fp_in);

    // 打开输出文件
    fp_out = fopen("out.txt", "w");
    if (fp_out == NULL) {
        printf("Open output file failed!\n");
        return 1;
    }

    // 输出总分最高的学生的姓名及总分
    fprintf(fp_out, "姓名:%s 总分:%d\n", stu[max_index].name, stu[max_index].total_score);

    // 关闭输出文件
    fclose(fp_out);

    return 0;
}