如何使用strtok将用户输入单词分隔符分隔为空格

时间:2017-10-19 01:33:17

标签: c strtok

为什么我只读了一个单词后才会出现分段错误?

如果我输入“为什么这不起作用”

我才回来

为什么

然后我遇到了分段错误。

我见过其他例子,但没有人像我在这里尝试的那样使用了用户输入。我只能阅读一个单词,但它不起作用。我尝试将所有%c更改为%s,但它没有帮助我。我也意识到分段错误指针指向不在内存中的某个地方,但我看不出它有什么问题。请帮我理解。

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

int main()
{
    char word[100];

    printf("Enter a sentence: ");
    scanf("%s", word);

    char *tok = strtok(word, " ");
    printf("%s\n", tok);

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

        if(tok == NULL)
            printf("finished\n");
    }

    return 0;
}

编辑:我更改了scanf(“%s”,word);到fgets(单词,100,stdin);现在它打印所有内容但我收到了分段错误。

2 个答案:

答案 0 :(得分:2)

正如评论中所指出的,您的第一个代码中至少存在两个问题。

  1. 不要使用scanf来读取要解析的字符串。请改用fgets

  2. 在使用之前(tok循环内部)<{1}}

  3. ,您不测试while是否为空

    通过调试很容易检测到这些问题,因此我建议您阅读how to debug small programs

    更正的代码应该是:

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char word[100];
    
        printf("Enter a sentence: ");
        /* read from stdin 
           note the `sizeof char`, if you need to change the size of `word`,
           you won't have to change this line. */
        fgets(word, sizeof word, stdin);
    
        /* initialize parser */
        char *tok = strtok(word, " ");
    
        while (tok != NULL)
        {
            /* printf token: it cannot be NULL here */
            printf("%s\n", tok);
    
            /* get next token*/
            tok = strtok(NULL, " ");
        }
        printf("finished\n");
    
        return 0;
    }
    

答案 1 :(得分:0)

此代码不正确

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

    if(tok == NULL)
        printf("finished\n");
}

假设你到达循环的最后一次传递......它会像你上次一样进入循环....所以你创建了一个tok = strtok(NULL, " ");返回(和分配){{1}因为没有更多的东西....然后你NULL它,它产生了seg错误。

只需将其更改为此内容,如果没有其他令牌可用,则不要进入循环。

printf(3)

或更简单

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

    /* you don't touch tok inside the loop, so you don't need to
     * test it again once you get inside */
}

/* if(tok == NULL)  <-- you always have tok == NULL here */
printf("finished\n");

此外,将while(tok = strtok(NULL, " ")) { printf("%s\n", tok); } printf("finished\n"); 添加到\n来电的第二个参数(在您的商家信息中的两个来电中,因为您只能有一个令牌,并且必须删除最后一行结尾)从第一次通话开始),就像你使用strtok(3)时一样,你通常会在字符串的末尾得到一个fgets(3)(你不想要):

\n
相关问题