这可能看起来非常明显,但 strtol 提供了对已解析整数的响应——但它在失败时为 0。如果我解析出来的整数是0怎么办?
最佳答案
errno
只保证在上溢/下溢(到 ERANGE
)的情况下被设置。对于其他错误,您必须检查 endptr
的值。引用 C89:
long int strtol(const char *nptr, char **endptr, int base);
If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.
通常 endptr 设置为指向输入字符串中最后一个字符转换后的下一个字符,因此如果它等于字符串的开头,则可以确定没有执行转换。例如,
char *nptr = "not a number", *endptr;
long n = strtol(nptr, &endptr, 10);
assert(nptr != endptr); //false
POSIX 包含一个方便的扩展,在这种情况下还将 errno
设置为 EINVAL
,但这是非标准的。
关于c - 如何使用 strtol 解析整数但将 "0"保留为有效值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127296/