使用strtok()与输入字符串或声明的字符串之间的区别

时间:2018-06-07 13:24:09

标签: c arrays string pointers

要了解{ANSI}中strtok()的行为,我需要两个代码。

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

int main()
{
    char str[101] = "This is";
    char *pch;
    printf("Splitting string %s into tokens : \n",str);
    pch = strtok(str," ");`enter code here`
    while(pch != NULL)
    {
        printf("%s\n",pch);
        pch = strtok(NULL, " ");
    }
    return 0;
}

该程序的结果是

Splitting string "This is " into tokens:
This
is

接下来,我稍微改了一下。

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

int main()
{
    char str[101] = ;
    char *pch;
    scanf("%s",str); //After launch program, I typed "This is "
    str[strcspn(str,"\n")] = '\0'
    printf("Splitting string %s into tokens : \n",str);
    pch = strtok(str," ");`enter code here`
    while(pch != NULL)
    {
        printf("%s\n",pch);
        pch = strtok(NULL, " ");
    }
    return 0;
}

打印

Splitting string "This" into tokens:
This

当我使用标准输入时,我无法理解为什么第二个字消失了。

1 个答案:

答案 0 :(得分:2)

问题不在于strtok,而在于您使用scanf"%s"格式说明符。该格式说明符读取空格分隔字符串,即您不能使用"%s"读取包含空格的任何内容。

自然的解决方案是使用fgets代替,您已经为“删除换行符”(scanf通常不会读取的内容)准备好了。

很明显,strtok无法参与,因为您在之前打印输入字符串甚至调用strtok