我有一个字符串看起来像这样“AGE:83”。我想从这个字符串中取出整数“83”,并且我知道我应该使用“sscanf”函数。然而,在这个字符串中没有空格。我应该怎么做?
使用以下内容:
const char *str = "AGE:83";
int age;
sscanf(str, "%*[^0-9]%d", &age);
if (sscanf(str, "%d", &age) != 1
&& sscanf(str, "%*[^0-9]%d", &age) != 1) {
// no number found;
return 1;
}
// age was correctly extracted from `str`
除非你知道前缀不包含'-'
,否则无法以此方式解析负数(使用格式"%*[^0-9-]%d"
)
你也可以使用字符串函数跳过前缀并将其余部分转换为atoi()
或strtol()
:
age = atoi(str + strcspn(str, "0123456789"));
AGE:
开头,您可以只使用以下代码将剩余的字符串转换:age = atoi(str + 4);
但如果字符串长度小于4个字符,这样做将导致未定义的行为,因为您可能会引用无效的地址。
%n
转换符,以便了解匹配的起始位置和/或结束位置。 - Jonathan Lefflerint age = atoi(str+4);
,从而避免使用sscanf
。 - Enzo Ferber