编写程序,文件“stu_info1.txt”包含学生的基本信息(姓名、学号、籍贯三项),现在需 要从该文件中读出信息,并依次为每位学生输入三门课程成绩,计算平均成绩,再将学生 完整信息(姓名、学号、籍贯、课程 1、课程 2、课程 3、平均分)写入文件 “stu_info2.txt”并保存于磁盘上。
时间: 2023-12-18 09:02:25 浏览: 40
好的,下面是一个实现您要求的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
typedef struct {
char name[20];
int id;
char hometown[20];
float score[3];
float avg;
} student;
int main() {
student students[MAX_STUDENTS];
int count = 0;
// 读取学生基本信息
FILE* fp1 = fopen("stu_info1.txt", "r");
if (fp1 == NULL) {
printf("Failed to open file!\n");
return 1;
}
while (fscanf(fp1, "%s %d %s", students[count].name, &students[count].id, students[count].hometown) != EOF) {
count++;
}
fclose(fp1);
// 输入学生成绩并计算平均分
for (int i = 0; i < count; i++) {
printf("Please enter the scores for student %s (id: %d):\n", students[i].name, students[i].id);
for (int j = 0; j < 3; j++) {
printf("Course %d: ", j+1);
scanf("%f", &students[i].score[j]);
}
float sum = 0;
for (int j = 0; j < 3; j++)
sum += students[i].score[j];
students[i].avg = sum / 3.0;
}
// 将学生信息写入文件
FILE* fp2 = fopen("stu_info2.txt", "w");
if (fp2 == NULL) {
printf("Failed to create file!\n");
return 1;
}
for (int i = 0; i < count; i++) {
fprintf(fp2, "%s %d %s %.2f %.2f %.2f %.2f\n", students[i].name, students[i].id, students[i].hometown, students[i].score[0], students[i].score[1], students[i].score[2], students[i].avg);
}
fclose(fp2);
printf("Done!\n");
return 0;
}
```
程序首先定义了一个结构体`student`,用于存储每个学生的姓名、学号、籍贯、3门课程的成绩和平均分。然后,我们使用`fopen`函数打开"stu_info1.txt"文件,并使用`fscanf`函数逐行读取学生的基本信息。
接下来,我们使用一个循环依次输入每个学生的3门课程成绩,计算平均成绩并存储到数组中。
最后,我们使用`fopen`函数创建"stu_info2.txt"文件,并使用`fprintf`函数将每个学生的完整信息写入文件中。
注意,这个程序只适用于文件中最多有100个学生数据的情况。如果文件中的学生数据超过了100个,需要修改代码中的`MAX_STUDENTS`常量。另外,程序中没有进行错误处理,需要加入相应的错误处理代码。同时,程序中存在基本信息和成绩信息的对应问题,需要保证两个文件中的数据一一对应。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)