【问题标题】:The difference between using strtok() to inputed string or declared string使用 strtok() 输入字符串或声明字符串的区别
【发布时间】:2018-06-07 13:24:08
【问题描述】:

为了理解strtok() 在 C ANSI 中的行为,我编写了两个代码。

#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

我不明白为什么我使用标准输入时第二个单词消失了。

【问题讨论】:

  • 第二个贴出的代码无法编译。请更正
  • 我希望您意识到使用输入格式说明符 '%s' 在第一个 white space I.E 处停止输入。在单词之间的空格

标签: c arrays string pointers


【解决方案1】:

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

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

很明显strtok 不能参与,因为您在调用strtok 之前 打印输入字符串。

【讨论】:

  • ".... scanf 通常不会读取的换行符" 会更好,因为 ".. scanf 说明符通常不会保存的换行符" 因为scanf() 确实读取了换行符。
  • @chux 更准确地说,scanf"%s" 会读取换行符,但将其保留在输入缓冲区中。
  • scanf"%s" 读取前导'\n' 和其他空格。然后读取并保存非空白,
猜你喜欢
  • 1970-01-01
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多