如何检查用户输入的数字不大于 LLONG_MAX 或小于 LLONG_MIN?

How to check that an user inputted number isn't bigger than LLONG_MAX or LOWER than LLONG_MIN?

我想检查用户输入的数字是否大于或小于告诉值。

我知道 atoll function 但它似乎并没有特别的帮助,基于未定义值的检查看起来不太令人信服。

我也知道我可以检查用户输入的字符串是否全是数字,在这种情况下我可以检查字符串的长度是否大于 LLONG_MAX 的长度或LLONG_MIN 一旦左边的 0 被删除,或者在两者的长度相同的情况下,我可以逐位检查,如果该数字中输入的数字的值大于 [= 的值12=] 或 LLONG_MIN 它将超出范围。

但我想必须有更好的方法来做到这一点。希望大家指点一下那条路是什么。

改用 strtoll 函数。

如果输入值超出范围,errno 设置为 ERANGE 并返回 LLONG_MINLLONG_MAX,具体取决于值是否下溢或溢出。

来自man page:

The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).

使用strtol。每 the strtol standard:

If the correct value is outside the range of representable values, {LONG_MIN}, {LONG_MAX}, {LLONG_MIN}, or {LLONG_MAX} shall be returned (according to the sign of the value), and errno set to [ERANGE].

所以:

errno = 0;
long long result = strtoll( inputStr, NULL, 0 );
if ( ( LLONG_MAX == result ) && ( ERANGE == errno ) )
{
    /* handle error */
   ...
}