来自"strsep"的字符串标记不打印(seg错误) [英] String token from `strsep` not printing (seg fault)
问题描述
我正在使用一小段代码来测试较大(入门)程序的功能,但是在显示从字符串中拔出的令牌时遇到了问题.
I'm using with a smaller piece of code to test functionality for a larger (beginner) program, but I have a problem displaying the token I've pulled out of a string.
我发现并使用过:
#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);
}
这很好用,一次将令牌作为字符串打印一个.
and this works fine, prints the tokens one at a time as strings.
然后,当我尝试移至用户输入的字符串时:
Then when I try and move to a user entered string:
#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);
行上出现段错误.我掌握了指针,数组和字符串的基础知识,但显然我缺少了一些东西,希望有人告诉我它是什么!
I get a seg fault on the printf("%s\n",found);
line. I'm getting the hang of basics of pointers, arrays and strings, but clearly I'm missing something, and would love for someone to tell me what it is!
也-如果我更改printf("%s\n",found);
的参数,例如到printf("%i\n",found);
我得到了一些随机性,但总是正确的数量,例如如果输入1/2/3
,我会得到三行垃圾,输入1111/2222
会得到两行.我尝试了%c,%i,%d,%p,它们都执行相同的操作,但是出现了%s seg错误.
Also - if I change the argument of printf("%s\n",found);
e.g. to printf("%i\n",found);
I get some randomness returned, but always the correct amount, e.g. If I enter 1/2/3
I get three lines of junk, entering 1111/2222
gives two lines. I tried %c, %i, %d, %p and they all do the same, but %s seg faults.
我完全迷住了.
推荐答案
此段错误是因为您缺少while
周围的括号.您将继续打印测试1",直到strsep
返回NULL
,然后尝试打印该结果(和段错误).
The segfault is because you're missing braces around your while
. You'll keep printing "Test 1" until strsep
returns NULL
, then you try to print that result (and segfault).
带有几个警告标记(可能是-Wall
),gcc可以在这里提供帮助:
With several warning flags (probably -Wall
), gcc helps out here:
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
周围添加花括号,该程序将按预期工作:
With braces added around the while
, the program works as expected:
./sep
Enter string: abc/def
Original string: 'abc/def'
Test 1abc
Test 1def
这篇关于来自"strsep"的字符串标记不打印(seg错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!