写入三个学生的C语言成绩,通过功能函数调用把三个学生的成绩按升序排序后,依次写入文件中,然后在屏幕上打印出来
时间: 2024-03-16 17:40:55 浏览: 53
好的,根据您的要求,我会为您提供相关的 C 代码示例。请注意,以下代码仅供参考,您需要根据具体情况进行修改和调整。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义学生结构体
typedef struct {
char name[20];
int score;
} Student;
// 定义比较函数
int cmp(const void *a, const void *b) {
return ((Student *)a)->score - ((Student *)b)->score;
}
// 定义写入文件函数
void writeToFile(Student students[], int n, const char *filename) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Cannot open file %s\n", filename);
return;
}
for (int i = 0; i < n; i++) {
fprintf(fp, "%s %d\n", students[i].name, students[i].score);
}
fclose(fp);
}
int main() {
// 定义学生数组并输入成绩
Student students[3];
for (int i = 0; i < 3; i++) {
printf("Please input student %d's name and score: ", i+1);
scanf("%s%d", students[i].name, &students[i].score);
}
// 排序
qsort(students, 3, sizeof(Student), cmp);
// 写入文件
writeToFile(students, 3, "result.txt");
// 输出排序结果
printf("Sorted result:\n");
for (int i = 0; i < 3; i++) {
printf("%s %d\n", students[i].name, students[i].score);
}
return 0;
}
```
在上述代码中,我们先定义了一个 `Student` 结构体,包括学生姓名和成绩两个成员。然后定义了一个比较函数 `cmp`,用于 `qsort` 函数排序时调用。接着定义了一个写入文件的函数 `writeToFile`,用于将排序后的结果写入文件中。最后在 `main` 函数中,我们输入三个学生的成绩,调用 `qsort` 函数进行排序,然后调用 `writeToFile` 函数将结果写入文件中,最后再输出排序结果到屏幕上。
注意,此处我们先调用 `writeToFile` 函数将排序结果写入文件中,再输出到屏幕上。如果您需要先输出到屏幕上再写入文件中,请自行修改相应代码。
阅读全文
相关推荐
















