gpt4 book ai didi

c - strtok() 跳过第一个标记

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:51 24 4
gpt4 key购买 nike

似乎无法弄清楚为什么这段代码不起作用。它应该非常简单。根据我所解决的问题,在 while(token) block 中分配了 id 数组,但是当我去打印 while(token) block 之外的所有 char 数组时,id 数组什么都不显示,但所有其他数组显示它们的内容。

int loadCatData(char* menuFile) {
char line[MAX_READ];
char id[ID_LEN];
char hotCold[MIN_DESC_LEN];
char name[MAX_NAME_LEN];
char description[MAX_DESC_LEN];
char delim[2] = "|";
char lineTemp[MAX_READ];
int count;
FILE *mfMenu = fopen(menuFile, "r");

while (fgets(line, sizeof(line), mfMenu)!=NULL) {
count = 0;
printf(line);

strcpy(lineTemp,line);

char* token = strtok(lineTemp, delim);

while (token) {
printf(token);
if (count == 0) {
strcpy(id, token);
}
if (count == 1) {
strcpy(hotCold, token);
}
if (count == 2) {
strcpy(name, token);
}
if (count == 3) {
strcpy(description, token);
}
printf("\n");
token = strtok(NULL, delim);
count = count + 1;
}
printf(id);
printf(hotCold);
printf(name);
printf(description);

}
fclose(mfMenu);
return true;
}

最佳答案

您是 strcpy 引起的缓冲区溢出错误的受害者。

发生的事情是 hotCold 数组太小,无法容纳您要填充的数据,但是 strcpy 不关心,也不知道没有足够的空间。所以它不断地将数据写入hotCold,然后用完空间,然后填充填充字节,然后填充id。只是不幸的是,hotCold 的终止空字节位于 id 的开头。

从使用 strcpy 切换到 strncpystrncat(我认为这比 strncpy 更好)。如果您对我所说的持怀疑态度,请在末尾添加一行代码,如下所示:

assert (strlen (hotCold) < MIN_DESC_LEN);

另一种选择是 id 字段被解释为特殊的 printf 格式说明符。以防万一,将 printf(id) 替换为 printf("%s", id)

关于c - strtok() 跳过第一个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467677/

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