gpt4 book ai didi

从文本文件创建链接列表

转载 作者:行者123 更新时间:2023-11-30 16:48:54 25 4
gpt4 key购买 nike

无法读取文本文件并将其存储在链接列表中。我正在读取一个包含名字、l 名、优先级和阅读级别的文件。我认为问题可能是我没有正确分配 strings/tempPtr,或者是我的循环持续运行。运行程序时,一直运行,没有段错误。

typedef struct Student{
char* firstName;
char* lastName;
int priority;
int readingLevel;
bookIds* wishlist;
struct Student* next;
}student;

student* buildStudentList(char* studentsFile, student* head)
{
int i;
FILE* fp;
student* tempPtr = NULL;
if((fp = fopen(studentsFile, "r")) == NULL)
{
printf("Unable to open file\n");
return 0;
}

student* current = NULL;
tempPtr = (student*)malloc(sizeof(student));
tempPtr->firstName = malloc(sizeof(char)* NAME);
tempPtr->lastName = malloc(sizeof(char)* NAME);

while(fscanf(fp, "%s %s %d %d",tempPtr->firstName, tempPtr->lastName, tempPtr->priority, tempPtr->readingLevel) != EOF)
{
tempPtr->next = NULL;
if(head == NULL)
{
head = tempPtr;
current = tempPtr;
tempPtr = (student*)malloc(sizeof(student));
}
else
{
current->next = tempPtr;
current = tempPtr;
tempPtr = (student*)malloc(sizeof(student));
}
}
free(tempPtr);
fclose(fp);
return head;
}

最佳答案

我建议您更改 student 结构,以便 firstNamelastName 是数组而不是指针。当它们始终具有相同大小时,无需使用动态分配。

typedef struct Student{
char firstName[NAME];
char lastName[NAME];
int priority;
int readingLevel;
bookIds* wishlist;
struct Student* next;
}student;

接下来,每当您分配新的student时,您都需要将wishListnext指针初始化为NULL.

当您调用fscanf()时,您需要将指针传递给您要填写的int成员。

您可以通过在一个地方执行 malloc() 来简化代码,而不是在循环之前执行,然后在 if 的每个分支中重复它。将输入读入局部变量,然后在成功后分配 student

typedef struct Student{
char firstName[NAME];
char lastName[NAME];
int priority;
int readingLevel;
bookIds* wishlist;
struct Student* next;
}student;

student* buildStudentList(char* studentsFile, student* head)
{
int i;
FILE* fp;
if((fp = fopen(studentsFile, "r")) == NULL)
{
printf("Unable to open file\n");
return 0;
}

student* current = NULL;

char firstName[NAME], lastName[NAME];
int priority, readingLevel;

while(fscanf(fp, "%s %s %d %d",firstName, lastName, &priority, &readingLevel) != EOF)
{
student* tempPtr = malloc(sizeof(student));
tempPtr->next = NULL;
tempPtr->wishlist = NULL;
strcpy(tempPtr->firstName, firstName);
strcpy(tempPtr->lastName, lastName);
tempPtr->priority = priority;
tempPtr->readingLevel = readingLevel;

if(head == NULL)
{
head = tempPtr;
}
else
{
current->next = tempPtr;
}
current = tempPtr;
}
fclose(fp);
return head;
}

关于从文本文件创建链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com