我无法在循环中使用fscanf将值读入链接列表。
程序最终编译并运行,但是print函数没有产生任何输出,这使我相信我的链接列表实际上并没有在我的读取函数中创建。
我设置了一些错误检查printf语句,并发现我的student * head值在返回main时返回NULL,然后发送到print函数。
我的职能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student{
char* first;
char* last;
int i;
int j;
struct Student* next;
}student;
int main(int argc, char* argv[])
{
student *start = NULL;
char *studentInput = argv[1];
start = buildStudentList(studentInput,start);
printStudents(start);
free_students(start);
return 0;
}
student* buildList(char* studentsFile, student* head)
{
student *current = head;
char *f = malloc(sizeof(char) * 25);
char *l = malloc(sizeof(char) * 25);
int prior,level = 0;
FILE *in = fopen(studentsFile, "r");
if(in == NULL)
{
printf("\nThe input file failed to open\n");
return NULL;
}
else
{
while(!feof(in))
{
fscanf(in, "%s %s %d %d",f,l,&prior,&level);
student *new = (student*)malloc(sizeof(student));
new->first = (char*)malloc(sizeof(char) * 25);
new->last = (char*)malloc(sizeof(char) * 25);
current = new;
strcpy(current->first,f);
strcpy(current->last,l);
current->i = prior;
current->j = level;
current->next = NULL;
current = current->next;
}
free(first);
free(last);
fclose(in);
return head;
}
}
void print(student* head)
{
if(head == NULL)
{
printf("head is null");
return;
}
student *current = head;
while(current->next != NULL)
{
printf("\n\nFirst Name: %s\nLast Name: %s\nPriority: %d\nReading Level: %d\n\n", current->first, current->last, current->i, current->j);
current = current->next;
printf("makes to loop");
}
}
void free_students(student *head)
{
if(head == NULL)
{
return;
}
student *current = head;
while(current->next != NULL)
{
student *temp = current;
current = current->next;
free(temp->first);
free(temp->last);
free(temp);
}
free(current->first);
free(current->last);
free(current);
}
此时输出为“head is null”。