用c语言写程序:文件“stu_info1.txt”包含学生的基本信息(姓名、学号、籍贯三项),现在需 要从该文件中读出信息,并依次为每位学生输入三门课程成绩,计算平均成绩,再将学生 完整信息(姓名、学号、籍贯、课程 1、课程 2、课程 3、平均分)写入文件 “stu_info2.txt”并保存于磁盘上。
时间: 2023-12-10 17:41:23 浏览: 70
以下是用 C 语言编写的程序:
```c
#include <stdio.h>
struct student {
char name[20];
char id[10];
char hometown[20];
float grade1, grade2, grade3, avg_grade;
};
int main() {
FILE *fp1, *fp2;
struct student stu;
fp1 = fopen("stu_info1.txt", "r");
fp2 = fopen("stu_info2.txt", "w");
while (fscanf(fp1, "%s %s %s", stu.name, stu.id, stu.hometown) != EOF) {
printf("Enter grades for %s: ", stu.name);
scanf("%f %f %f", &stu.grade1, &stu.grade2, &stu.grade3);
stu.avg_grade = (stu.grade1 + stu.grade2 + stu.grade3) / 3.0;
fprintf(fp2, "%s %s %s %.2f %.2f %.2f %.2f\n", stu.name, stu.id, stu.hometown,
stu.grade1, stu.grade2, stu.grade3, stu.avg_grade);
}
fclose(fp1);
fclose(fp2);
return 0;
}
```
该程序首先定义了一个 `struct student` 结构体,其中包含姓名、学号、籍贯、三门课程成绩和平均成绩等信息。
程序接着打开了两个文件,`stu_info1.txt` 用于读取学生基本信息,`stu_info2.txt` 用于写入完整信息。在循环中,程序从 `stu_info1.txt` 中读取一行学生基本信息,输出提示信息并读取三门课程成绩,计算平均成绩,然后将完整信息写入 `stu_info2.txt` 中。
注意,程序中使用 `fscanf` 函数从文件读取信息,使用 `fprintf` 函数向文件写入信息,格式化字符串中使用了 `%s` 表示字符串、`%f` 表示浮点数。同时,程序中使用了 `fclose` 函数关闭文件。
编译并运行该程序后,会在磁盘上生成 `stu_info2.txt` 文件,其中包含所有学生的完整信息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)