【发布时间】:2020-10-22 07:20:27
【问题描述】:
我尝试从文件中获取学生的姓名和代码并将其保存到结构中。文件是这样的
6, student1
2, student2
9, student3
这是我的尝试。你能告诉我这段代码有什么问题吗?
#include <stdio.h>
#include <stdlib.h>
#define N 20
struct Students {
char studentName[N];
int code;
};
void student() {
FILE *f = fopen("file.txt", "r");
struct Students *ptr;
int i;
ptr = malloc(sizeof(struct Students));
if (ptr == NULL){
printf("memory cannot be allocated");
exit(1);
}
if (f == NULL) {
printf("can't open the file");
exit(1);
}
i=0;
while (feof(f)) {
fscanf(f, "%d, %s\n", &(ptr+i)->code, &(ptr+i)->studentName);
ptr = realloc(ptr, sizeof(struct Students) * i);
i++;
}
}
int main() {
student();
return 0;
}
【问题讨论】:
-
while(feof(f))肯定是不对的。您的意思可能是while(!feof(f)),但这也是错误的,请参阅stackoverflow.com/questions/5431941/… -
另外,你的
realloc逻辑是错误的。仔细想一想:每一步,ptr可以容纳多少个结构,最后一个的索引是什么,你要写什么索引? -
另外
fscanf(f, "%d, %s\n", &(ptr+i)->code, (ptr+i)->studentName);,&(ptr+i)->studentName应该是(ptr+i)->studentName或者更好ptr[i].studentName -
在你的第一个 realloc 中,你乘以 i = 0。这肯定不是你想要的