简体   繁体   中英

[C]-Splitting string into 2 strings

I'm a C beginner and working on a program right now. This is just a little part of it.

I want, that whenever I enter "set A" the program outputs "Hallo 1" and "Hallo 2" and whenever I only enter "set" the program should only output "Hallo 1". My problem is, that when I only enter "set", it crashes... and I have no idea why

#include <stdio.h>
#include <string.h>
int main()
{
    char command[128];
    printf("ep> ");
    scanf(" %[^\n]%*c", command);

    char *token;
    char *token2;
    char *search = " ";

    token = strtok(command, search);

    token2 = strtok(NULL, search);


      if  (strcmp(token, "set") == 0)
        {
            printf("Hallo1\n");
                if (strcmp(token2, "A") == 0)
            {
                    printf("Hallo2\n");
                    return;
            }
            return;
        }

return 0;
}

It's because token2 is NULL in the call below :

 token2 = strtok(NULL, search); // NULL when input is "set"

so

 if (strcmp(token2, "A") == 0) // Segmentation fault

will lead you to a segmentation fault

You could try with this:

if (token2 && strcmp(token2, "A") == 0)

You can't strcmp with a NULL string, which is what you get if you call strtok a second time with only " set " as input, as that will give you the segmentation fault you got there.

You could first check if token2 is not NULL , like this:

if (token2)

will be true if token2 is not NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM