[C]-将字符串拆分为 2 个字符串
[C]-Splitting string into 2 strings
我是 C 初学者,现在正在开发一个程序。
这只是其中的一小部分。
我想要,每当我输入 "set A" 程序输出 "Hallo 1" 和 "Hallo 2" 并且每当我只输入 "set" 程序应该只输出 "Hallo 1".
我的问题是,当我只输入 "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;
}
这是因为 token2 在下面的调用中为 NULL :
token2 = strtok(NULL, search); // NULL when input is "set"
所以
if (strcmp(token2, "A") == 0) // Segmentation fault
将导致您出现分段错误
你可以试试这个:
if (token2 && strcmp(token2, "A") == 0)
您不能 strcmp
使用 NULL 字符串,这是您第二次调用 strtok
时仅输入“set
”所得到的结果,因为那样会给你你到达那里的分段错误。
您可以先检查 token2 是否不是 NULL
,像这样:
if (token2)
如果 token2 不是 NULL
, 将为真。
我是 C 初学者,现在正在开发一个程序。 这只是其中的一小部分。
我想要,每当我输入 "set A" 程序输出 "Hallo 1" 和 "Hallo 2" 并且每当我只输入 "set" 程序应该只输出 "Hallo 1". 我的问题是,当我只输入 "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;
}
这是因为 token2 在下面的调用中为 NULL :
token2 = strtok(NULL, search); // NULL when input is "set"
所以
if (strcmp(token2, "A") == 0) // Segmentation fault
将导致您出现分段错误
你可以试试这个:
if (token2 && strcmp(token2, "A") == 0)
您不能 strcmp
使用 NULL 字符串,这是您第二次调用 strtok
时仅输入“set
”所得到的结果,因为那样会给你你到达那里的分段错误。
您可以先检查 token2 是否不是 NULL
,像这样:
if (token2)
如果 token2 不是 NULL
,将为真。