我正在尝试从文件读取行输入,正确解析该行,并将该行中的三个信息字段添加到链接列表中的节点上。
这是我从文件功能中读取的内容:
int readFile(char* file)
{
FILE *fp = fopen(file,"r");
char ch;
char line[50];
char string1[100];
char string2[100];
char string3[100];
char endLine[2];
int i = 0;
while(fscanf(fp, "%[^\t]\t%[^\t]\t%[^\n]", string1, string2, string3) == 3)
{
printf( "%s\t%s\t%s\n", string1, string2, string3);
addNode(string1, string2, string3, head, tail);
}
printNodes();
fclose(fp);
return 0;
}
这是我的addNode函数:
// create stuff
Entry *entry = malloc(sizeof(Entry));
entry->name = string1;
entry->address = string2;
entry->number = string3;
Node* node = malloc(sizeof(Node));
node->entry = entry;
node->next = NULL;
// Empty list
if(head->next == NULL)
{
head->next = node;
}
// Else, add to the end of the list
else
{
Node* temp = head->next;
while(temp->next!= NULL)
{
temp = temp->next;
}
temp->next = node;
}
当我调用printNodes时遇到问题,并且只打印了最后一个读取节点的信息X次,其中X是我应该拥有的唯一节点的数量。我想我每次创建新节点时都会覆盖旧节点,但我不完全确定,因为这是我第一次使用原始C代码。
再次感谢!
编辑: 这是printNodes()函数:
int printNodes(Node* head)
{
Node *temp = head->next;
while(temp->next != NULL)
{
printf("\n%s\t%s\t%s\n", temp->entry->name, temp->entry->address, temp->entry->number);
temp = temp->next;
}
return 0;
}
答案 0 :(得分:1)
你的问题在这里:
entry->name = string1;
entry->address = string2;
entry->number = string3;
您为每个节点提供相同的内存位置。这些字符串包含您在致电printNodes()
时读到的最后值。