简体   繁体   English

[C]-将字符串拆分为2个字符串

[英][C]-Splitting string into 2 strings

I'm a C beginner and working on a program right now. 我是C语言的初学者,现在正在开发程序。 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". 我想要,每当我输入“ set A”时程序都会输出“ Hallo 1”和“ Hallo 2”,而每当我仅输入“ set”时程序应仅输出“ Hallo 1”。 My problem is, that when I only enter "set", it crashes... and I have no idea why 我的问题是,当我仅输入“ set”时,它崩溃了……我不知道为什么

#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为NULL:

 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. 您不能使用NULL字符串来进行strcmp ,这是如果您仅以“ set ”作为输入第二次调用strtok时所得到的结果,因为这会给您到达那里的分段错误。

You could first check if token2 is not NULL , like this: 您可以先检查token2是否不为NULL ,如下所示:

if (token2)

will be true if token2 is not NULL . 如果token2不为NULL则为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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