Search code examples
cstrtok

How to seperate user input word delimiter as space using strtok


Why am I getting a segmentation fault after only reading one word?

If I enter "why is this not work"

I only get back

why

and then I get a segmentation fault.

I've seen other examples but none have used user input like I am trying to do here. I can only read one word and it won't work. I tried changing all the %c to %s but it is not helping me. I also realize segmentation fault is pointer pointing to somewhere not in memory but I cannot see what is wrong with it. Please help me understand.

#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;
}

EDIT: I changed scanf("%s", word); to fgets(word, 100, stdin); and now it prints everything but I get a Segmentation fault.


Solution

  • As pointed in comments, there is at least two problems in your first code.

    1. Do not use scanf to read a string that you want to parse. Use fgets instead.

    2. You do not test that tok is not NULL before using it (inside the while loop)

    Such problems would have been easily detected with debugging, so I encourage you to read how to debug small programs

    Corrected code should be like:

    #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;
    }