编写C语言程序,文件“stu_info1.txt”包含学生的基本信息(姓名、学号、籍贯三项),现在需 要从该文件中读出信息,并依次为每位学生输入三门课程成绩,计算平均成绩,再将学生 完整信息(姓名、学号、籍贯、课程 1、课程 2、课程 3、平均分)写入文件 “stu_info2.txt”并保存于磁盘上。
时间: 2023-12-16 07:03:09 浏览: 28
以下是一个可以实现这个需求的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 20
#define MAX_ID_LEN 10
#define MAX_PLACE_LEN 20
struct student {
char name[MAX_NAME_LEN];
char id[MAX_ID_LEN];
char place[MAX_PLACE_LEN];
float score1;
float score2;
float score3;
float average;
};
int main() {
FILE *fp1, *fp2;
struct student stu;
char file1[] = "stu_info1.txt";
char file2[] = "stu_info2.txt";
fp1 = fopen(file1, "r");
if (fp1 == NULL) {
printf("Failed to open file %s\n", file1);
return 1;
}
fp2 = fopen(file2, "w");
if (fp2 == NULL) {
printf("Failed to open file %s\n", file2);
return 1;
}
while (fscanf(fp1, "%s %s %s", stu.name, stu.id, stu.place) == 3) {
printf("Please enter the scores for student %s (ID: %s):\n", stu.name, stu.id);
scanf("%f %f %f", &stu.score1, &stu.score2, &stu.score3);
stu.average = (stu.score1 + stu.score2 + stu.score3) / 3;
fprintf(fp2, "%s %s %s %.2f %.2f %.2f %.2f\n", stu.name, stu.id, stu.place, stu.score1, stu.score2, stu.score3, stu.average);
}
fclose(fp1);
fclose(fp2);
return 0;
}
```
这个程序首先打开了文件“stu_info1.txt”和“stu_info2.txt”,并定义了一个结构体 `student` 表示每个学生的信息。然后,程序逐行读取文件“stu_info1.txt”中的学生信息,要求用户输入每位学生的三门课程成绩,并计算平均成绩。最后,程序将每个学生的完整信息(包括姓名、学号、籍贯、三门课程成绩和平均分)写入文件“stu_info2.txt”。如果在打开文件时出现错误,程序会输出错误信息并返回1。
相关推荐
![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)