C implementation - use the structure to enter student grades into the file (detailed)

Write in front (import)

        Be sure to execute the program before: "Create a text document on the desktop", the name is student  . To avoid program execution errors, of course, you can also modify the relative path of the file to open, and modify the path of the file student.txt in "fopen("student.txt", "r")" in the following program  .

Code

        Idea: first store the data in the array, and then write it to the file separately. (The program has been annotated in detail and will not be repeated here)

//导入头文件
#include<stdio.h>
#include<stdlib.h>

//定义结构体 
typedef struct{
	char name[20];//姓名 
    int ID;//学号 
    int chinese;//语文成绩 
    int math;//数学成绩 
    int English;//英语成绩 
    float avargrade;//平均成绩 
    
}Student;

//主函数
int main(){
    FILE *fp;//定义文件指针 
    Student stu[5];//定义结构体数组stu,容量为 5 
    int i;//控制循环
    float avargrade=0;//记录平均成绩 
    printf("请输入5个同学的信息:姓名 学号 语文成绩 数学成绩 英语成绩:\n");//信息提示 
    for(i=0;i<5;i++){
        scanf("%s %d %d %d %d",stu[i].name,&(stu[i].ID),&(stu[i].chinese),&(stu[i].math),&(stu[i].English));
        stu[i].avargrade=(stu[i].chinese+stu[i].math+stu[i].English)/3;
    }
    //判断文件是否存在 
    if((fp=fopen("student","w"))==NULL){
        printf("文件打开失败!\n");
        exit(0);
    }
    //输出 
    for(i=0;i<5;i++){
    	fprintf(fp,"%s %d %d %d %d %d\n",stu[i].name,stu[i].ID,stu[i].chinese,stu[i].math,stu[i].English, 
                stu[i].avargrade);
	}
    fclose(fp);//关闭文件 
    return 0;
}

operation result

 (1) In the program, the content of the file is as shown in (2).

(2) As shown in the figure below, the contents of the file:

 

Guess you like

Origin blog.csdn.net/m0_54158068/article/details/124372971