【发布时间】:2021-12-13 02:49:00
【问题描述】:
我正在尝试使用 strtok() 从 .txt 文件初始化链接列表。
但是当我想初始化名称(我的结构的第一个元素)时,strtok 返回一个“(null)”。
但是,当我 printf() 我的 strElement 时,我得到了预期的名称。
治愈.c
#include "heals.h"
ListeHeals* initHeals()
{
ListeHeals* ListeHeals = malloc(sizeof(*ListeHeals));
char const* const fileName = "items/heals.txt";
FILE* file = fopen(fileName, "r");
if (file == NULL)
{
printf("Fichier non ouvert");
}
char line[256];
const char * separator = "|";
int count = 0;
while (fgets(line, sizeof(line), file)) {
char* strElement = strtok (line, separator);
while (strElement != NULL) {
Heals* heal = malloc(sizeof(*heal));
if(count == 0)
{
printf("%s\n", strElement);
heal->name = strElement;
}
else if(count == 1)
{
heal->heal = atoi(strElement);
ListeHeals->first = heal;
}
strElement = strtok (NULL, separator);
count += 1;
}
count = 0;
}
fclose(file);
return ListeHeals;
}
void printListeHeals(ListeHeals* ListeHeals)
{
if (ListeHeals == NULL)
{
exit(EXIT_FAILURE);
}
Heals* actual = ListeHeals->first;
while (actual != NULL)
{
printf("Nom : %s\n", actual->name);
printf("heal : %d\n\n", actual->heal);
actual = actual->next;
}
printf("NULL\n");
}
The output 第一行是我的 printf。
这是文件heals.txt:
Potion de vie I|30
Potion de vie II|80
Potion de vie III|200
愈合结构(heal.h):
#ifndef heals_h
#define heals_h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Heals
{
char* name;
int heal;
struct Heals* next;
};
typedef struct Heals Heals;
struct ListeHeals
{
struct Heals* first;
};
typedef struct ListeHeals ListeHeals;
ListeHeals* initHeals();
void printListeHeals(ListeHeals* ListeHeals);
#endif
我期望的输出:
nom : Potion de vie I // I have (null)
heal : 30 // I already have it
欢迎任何帮助谢谢!
【问题讨论】:
-
那么另外两行是什么?如果
strtok将在第一个令牌上返回NULL,您将如何进入您的while(strElement !=NULL循环?我假设您弄乱了循环或您显示的代码之外的其他内容。请显示您的输入(文件内容)、输出和预期输出。连同MCVE。 -
您似乎从文件的 1 行中读取了
heal的多个字段,但是您为一行中的每个标记上的新元素分配了内存。这看起来很奇怪,但您的代码太不完整,无法判断。 -
另外两行是愈合对象的打印
-
我对@987654334@ 感到困惑如果
heal->name是char *,那么您将其指向本地line数组,该数组在函数末尾超出范围 - 然后您以后不能在程序中使用heal->name。 ``heal->name` 应该是一个字符数组,你应该使用strcpy将字符串放入其中。 -
您应该在调试器中运行您的程序并单步执行它。我猜你有很多错误,但
strtok没问题。您永远不会将列表中的节点链接到另一个节点。您只需插入first。此外,您每行分配 2 个结构。那么你永远不会重置count。除此之外,您应该复制字符串而不是分配指针。
标签: c struct linked-list strtok