gpt4 book ai didi

c - 如何从C中的文本文件中读取数据到链表中

转载 作者:行者123 更新时间:2023-11-30 17:03:01 26 4
gpt4 key购买 nike

我对 C 编程还很陌生,我正在尝试构建一个控制台应用程序,它将一些用户调查数据接收到单链表中并从中生成统计数据。

主要思想是,每次应用程序用户打开应用程序时,现有的调查数据都会从文本文件加载到链接列表节点中。然后用户可以根据需要操作数据。

我的问题是,每次调用 importList 函数时应用程序都会崩溃,而且我不知道问题出在哪里。如果有人能指出我的错误在哪里,我将非常感激。谢谢。

以下是从文本文件导入数据的函数:

void importList(struct nodeList** head)
{

//set up the linked list node by node
struct nodeList *temp;
temp =(struct nodeList*)malloc(sizeof(struct nodeList));
temp = *head;

//open survey data file in read mode to import existing survey data
openSurveyFile();

//read in data that's in the text file to nodes in linked list
while(!feof(surFPtr))
{
//import data from file. All data except address is held in single word lines.
fscanf(surFPtr, "%d", &temp->PPS);
fscanf(surFPtr, "%s", temp->name);
fscanf(surFPtr, "%s", temp->surname);
fgets(temp->address, 50, surFPtr);//since address is a multiword string the list needs to read the entire line
fscanf(surFPtr, "%s", temp->eMail);
fscanf(surFPtr, "%d", &temp->age);
fscanf(surFPtr, "%d", &temp->income);
fscanf(surFPtr, "%s", temp->gender);
fscanf(surFPtr, "%d", &temp->exercise);
fscanf(surFPtr, "%d", &temp->alcohol);
fscanf(surFPtr, "%d", &temp->smoking);
fflush(stdin);

//allocate memory for the next node in list
temp->next =(struct nodeList*)malloc(sizeof(struct nodeList));
temp = temp->next;//move on to next node
}
//close survey data file once all data is imported
closeSurveyFile();
}//end of importList function

最佳答案

开头附近有一个错误:由于您将 temp 替换为 *head,因此您将丢失首先分配到 temp 中的内存。如果调用此函数时 *head 为 null,则在取消引用指针时会出现异常。也许您想要执行 *head = temp; 来取回列表的头部?

关于c - 如何从C中的文本文件中读取数据到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308197/

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