【发布时间】:2020-08-15 20:58:39
【问题描述】:
我想读取一个看起来像这样的文件:
Spyros 1
George 2
John 3
我想将每个学生存储在一个结构中:
typedef struct studentR *student;
struct studentR{
char name[MAXSTRING];
int id;
student next;
};
我已经编写了以下代码,它可以满足我的需求,但仅适用于第一行。如何将其移至下一行?
while(fscanf(fp, "%s %d", st->name, &st->id) != EOF){
l = list_push_back(l, st->name, st->id);
}
这里是 list_push_back
//enters the new student in the end of the list
list list_push_back(list l, char *name, int id){
student new_student = (student)malloc(sizeof(struct studentR));
assert(new_student);
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
//push payload(stsudent data) at the top if the list is empty
if (list_isempty(l))
{
l->head = new_student;
l->tail = new_student->next;
l->size++;
}else{
//push the payload(student data) at the bottom if the list is NOT empty
student last = (student)malloc(sizeof(struct studentR));
assert(last);
last->next = new_student;
l->tail = new_student;
l->size++;
}
return l;
}
【问题讨论】:
-
我知道隐藏指针的事情。我们的老师给我们看了。不知道为什么。我还包括了 list_push_back 函数
-
HInt:当第一个节点添加到您的列表时,
head和tailboth 应该指向什么?您的代码做了什么不符合该标准?此外,您正在泄漏内存,并且在非空列表情况下未插入包含任何数据的节点。关于指针类型别名,您的老师向您展示最终是一个坏习惯是一种证明,不一定是奉承。
标签: c list file struct file-io