#include <stdio.h>
int main()
{
char string[80]="abcdef";
char buffer[80];
int num;
sscanf(string,"%*[^0-9a-fA-F]%n%s",&num,buffer);
printf("%d\n",num);
puts(buffer);
return 0;
}
Output:
输出:
-149278720
And what I expect is
而我的期望是
0
abcdef
I believe that the regex %*[^0-9a-fA-F]
discards all characters other than "xdigits"
, however, when the first character in the string is a "xdigit"
, sscanf
seems to return instantly.
我相信正则表达式%* [^ 0-9a-fA-F]丢弃除“xdigits”之外的所有字符,但是,当字符串中的第一个字符是“xdigit”时,sscanf似乎立即返回。
How can I fix this?
我怎样才能解决这个问题?
1 个解决方案
#1
2
%*[^0-9a-fA-F]
matches a non-empty sequence of characters that aren't in the character set. Since you don't have any non-hexdigits at the beginning of the string, this conversion fails and sscanf
returns immediately.
%* [^ 0-9a-fA-F]匹配不在字符集中的非空字符序列。由于您在字符串的开头没有任何非hexdigits,因此此转换失败并且sscanf立即返回。
As far as I can tell, there's no way to make this optional in sscanf
. If you just want to skip over the non-hexdigits, use strcspn()
.
据我所知,没有办法在sscanf中使这个可选。如果您只想跳过非hexdigits,请使用strcspn()。
num = strcspn(string, "0123456789abcdefABCDEF");
strcpy(buf, string+num);
#1
2
%*[^0-9a-fA-F]
matches a non-empty sequence of characters that aren't in the character set. Since you don't have any non-hexdigits at the beginning of the string, this conversion fails and sscanf
returns immediately.
%* [^ 0-9a-fA-F]匹配不在字符集中的非空字符序列。由于您在字符串的开头没有任何非hexdigits,因此此转换失败并且sscanf立即返回。
As far as I can tell, there's no way to make this optional in sscanf
. If you just want to skip over the non-hexdigits, use strcspn()
.
据我所知,没有办法在sscanf中使这个可选。如果您只想跳过非hexdigits,请使用strcspn()。
num = strcspn(string, "0123456789abcdefABCDEF");
strcpy(buf, string+num);