为了对您已有的代码进行最小的更改,您可以使用以下%n功能sscanf:
int chars_read;
r[1] = sscanf(c, "%d%n", &r[0], &chars_read);
如果chars_read小于字符串的长度,sscanf则不消耗所有字符,因此字符串不完全由单个整数组成。
Linux 文档scanf指出,技术勘误 1引入的附加示例与标准相矛盾,但与此同时,标准已更新以解决冲突。sscanf面对您可能遇到的不确定的实现行为,您可以如何解释结果:
switch (r[1]) {
case EOF: // empty string
break;
case 0: // doesn't start with numeric characters
break;
case 1: // starts with number; sscanf follows standards
case 2: // starts with number; sscanf follows TC1
if (c[chars_read] == '\0')
r[1] = 1; // we read entire string
else
r[1] = 0; // didn't read entire string; pretend we read nothing
break;
default: // shouldn't happen
assert(FALSE);
}