【发布时间】:2014-05-23 10:01:34
【问题描述】:
示例代码:
#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?
我正在使用另一个变量并对其进行初始化,并且还使用了另一个令牌变量。如何获得期望结果?
【问题讨论】: