gpt4 book ai didi

c - 重用 strtok 为 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:59 25 4
gpt4 key购买 nike

示例代码:

#include <stdio.h>
#include <string.h>

int main()
{
char str[1024];
char *buff, *temp, *result = NULL;
char tok[] = " ";
printf("enter string:\n");
gets(str);

buff = str;

result = strtok(buff, tok);

while (result != NULL)
{
printf("%s\n", result);
result = strtok(NULL, tok);
}

printf("\n");

char tok1[] = " ";
temp = str;
result = strtok(temp, tok1);

while (result != NULL)
{
printf("%s\n", result);
result = strtok(NULL, tok1);
}
}

以上代码输出如下:

enter string:
Hello how are you
Hello
how
are
you

Hello

但是,我希望输出是:

enter string:
Hello how are you
Hello
how
are
you

Hello
how
are
you

为什么 strtok 在打印第一个单词(即“hello”)后返回 NULL?我正在使用另一个变量并对其进行初始化,还使用另一个标记变量。如何获得想要的结果?

最佳答案

strtok() 修改输入字符串。因此,在第一轮标记化之后,原始字符串 str 已被修改(因为 temp 指向 str)。

因此,在将字符串 传递给 strtok() 之前,先复制一份字符串。

其他改进:

1) 不要使用已弃用的 gets()。请改用 fgets() 以避免潜在的缓冲区溢出。
2) 使用 strtok_r() 因为它是可重入的。

关于c - 重用 strtok 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826302/

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