前言
彩笔写个大作业每个功能都要卡好久。唉,带专人太难了,呜呜呜。
吐槽:chatgpt不靠谱,我改了一下,让它能跑起来。
程序要求
1. 输入学生姓名,成绩(连续两个空格换行),并保存在./score.txt中。
2. 将./score.txt中的成绩由大到小排序,赋上排名,覆盖原有文件。
3. 按成绩由大到小打印。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
//成绩写入,读取排名
struct student {
char name[20];
int score;
int rank;
};
int compare_students(const void *a, const void *b){
struct student *s1 = (struct student *)a;
struct student *s2 = (struct student *)b;
return s2->score - s1->score;//后面大于前面就置换
}
int main() {
struct student students[MAX_STUDENTS],a[MAX_STUDENTS];
//不知道为啥,上面的结构体赋初值(0)会导致没法结束输入
int num_students = 0;
int i=0,j;
char ch;
int hnum;
//写
FILE *file = fopen(".//score.txt", "a+");
if(file==NULL){
file=fopen(".//score.txt","wb+");
}
while(i<10){
int w=0;//每行第几字符
while((ch=getchar())!=' '){
if(ch=='\n'){
hnum+=1;
}else{
hnum=0;//不是连续的两个\n就清零
}
if(hnum==2){
break;
}else if(hnum==1){
continue;//防止数组存入\n
}
a[i].name[w]=ch;
w++;
}
a[i].name[w]='\0';//数组末尾补0
if(hnum==2){
break;
}
scanf("%d",&a[i].score);
a[i].rank=0;
i++;
}
for(j=0;j<i;j++){
fwrite(&a[j],1,sizeof(struct student),file);
}
fclose(file);
//下面开始排序
file = fopen(".//score.txt", "r");
if(file==NULL){
printf("Unable to open file.\n");
}
//文件读操作(fread),必须先读一次再接while循环判断是否到文件末尾,不然下面for会多一次
fread(&students[num_students], sizeof(struct student), 1, file);
while(!feof(file)){
num_students++;
fread(&students[num_students], sizeof(struct student), 1, file);
}
fclose(file);
qsort(students, num_students, sizeof(struct student), compare_students);
//从大到小排序
for (i = 0; i < num_students; i++) {
students[i].rank = i + 1;
}
file = fopen(".//score.txt", "w+");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
for (i = 0; i < num_students; i++) {
fwrite(&students[i],1,sizeof(struct student),file);
}
fclose(file);
//打印排名
file = fopen(".//score.txt", "r");
printf("Students sorted by rank:\n");
fread(&students[j],1,sizeof(struct student),file);
while (!feof(file)) {
printf("%d. %s: %d\n", students[j].rank, students[j].name, students[j].score);
fread(&students[j],1,sizeof(struct student),file);
}
fclose(file);
return 0;
}