修改代码错误int read_student_info(student students[]) { int i = 0; FILE *fp; fp = fopen("d:/学生系统/student.txt", "r"); if (fp == NULL) { printf("打开文件失败!\n"); return 0; } while (fscanf(fp, "%s %s %s %d/%d/%d %d %d %d", &students[num_students].num, students[num_students].name, students[num_students].sex, &students[num_students].year, &students[num_students].month, &students[num_students].day, &students[num_students].score[1], &students[num_students].score[2], &students[num_students].score[3]) != EOF) { students[num_students].total = students[num_students].score[1] + students[num_students].score[2] + students[num_students].score[3]; students[num_students].average = students[num_students].total / 3; num_students++; if (num_students>=MAX_STUDENTS) { printf("已有太多学生信息!\n"); break; } } fclose(fp); return num_students; }
时间: 2024-02-25 12:58:36 浏览: 185
linux_file_op.zip_file操作_linux fopen_open
在代码中,缺少定义变量num_students和MAX_STUDENTS,需要加上如下定义:
```
#define MAX_STUDENTS 100 // 假设最多有100个学生信息
int read_student_info(student students[]) {
int i = 0;
int num_students = 0; // 定义记录学生个数的变量
FILE *fp;
fp = fopen("d:/学生系统/student.txt", "r");
if (fp == NULL) {
printf("打开文件失败!\n");
return 0;
}
while (fscanf(fp, "%s %s %s %d/%d/%d %d %d %d",
&students[num_students].num,
students[num_students].name,
students[num_students].sex,
&students[num_students].year,
&students[num_students].month,
&students[num_students].day,
&students[num_students].score[1],
&students[num_students].score[2],
&students[num_students].score[3]) != EOF) {
students[num_students].total = students[num_students].score[1] + students[num_students].score[2] + students[num_students].score[3];
students[num_students].average = students[num_students].total / 3;
num_students++;
if (num_students >= MAX_STUDENTS) {
printf("已有太多学生信息!\n");
break;
}
}
fclose(fp);
return num_students;
}
```
这样修改后,代码就能正确地读取学生信息并返回学生个数了。
阅读全文