gpt4 book ai didi

c - 来自 `strsep` 的字符串标记未打印(段错误)

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:36 27 4
gpt4 key购买 nike

我正在使用一小段代码来测试较大(初学者)程序的功能,但我在显示从字符串中提取的 token 时遇到问题。

我发现并使用了:

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

int main()
{

char *string, *found;

string = strdup ("1/2/3");
printf("Original string: '%s'\n",string);

while ((found = strsep(&string,"/")) != NULL )
printf ("%s\n",found);

return (0);
}

这很好用,一次将一个标记打印为字符串。

然后当我尝试移动到用户输入的字符串时:

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

int main()
{
char string[13];
char *found, *cp = string;

fprintf(stderr, "\nEnter string: ");
scanf("%12s",string);
printf("Original string: '%s'\n",string);

while((found = strsep(&cp,"/,-")) != NULL )
printf("Test 1"); /*To pinpoint where the seg fault arises*/
printf("%s\n",found);

return(0);
}

我在 printf("%s\n",found); 行遇到段错误。我掌握了指针、数组和字符串的基础知识,但显然我遗漏了一些东西,希望有人告诉我它是什么!

此外 - 如果我更改 printf("%s\n",found); 的参数,例如到 printf("%i\n",found); 我得到了一些随机性返回,但总是正确的数量,例如如果我输入 1/2/3 我得到三行垃圾,输入 1111/2222 得到两行。我尝试了 %c、%i、%d、%p,它们都做同样的事情,但是 %s 段错误。

我完全被难住了。

最佳答案

段错误是因为您在 while 周围缺少大括号。您将继续打印“测试 1”,直到 strsep 返回 NULL,然后您尝试打印该结果(和段错误)。

有几个警告标志(可能是 -Wall),gcc 在这里提供帮助:

sep.c:13:3: warning: this ‘while’ clause does not guard... [-Wmisleading-indentation]
while((found = strsep(&cp,"/,-")) != NULL )
^~~~~
sep.c:15:5: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the ‘while’
printf("%s\n",found);
^~~~~~

while 周围添加大括号后,程序按预期运行:

./sep 

Enter string: abc/def
Original string: 'abc/def'
Test 1abc
Test 1def

关于c - 来自 `strsep` 的字符串标记未打印(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com