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

百般思念 提交于 2019-12-24 04:23:12

问题


I want to check if an user inputted number is bigger or lower than the told values.

I know about atoll function but it doesn't seem to be specially helpful, basing the check on a undefined value doesn't look too convincing.

I also know that I could check if the string the user has inputted is all digits, in this case I could check for things as if the length of the string is bigger than the length of LLONG_MAX or LLONG_MIN once 0s on the left are removed, or in the case the length of both is the same I could go checking digit by digit and if the value of the inputted number in that digit is bigger than the value of LLONG_MAX or LLONG_MIN the it would be out of range.

But I guess there has to be a better way to do this. Hope you can give me tips about which that way is.


回答1:


Use the strtoll function instead.

In case the inputted value is out of range, errno is set to ERANGE and either LLONG_MIN or LLONG_MAX are returned, depending on whether the value underflows or overflows.

From the 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).




回答2:


Use strtol. Per 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].

So:

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


来源:https://stackoverflow.com/questions/40406860/how-to-check-that-an-user-inputted-number-isnt-bigger-than-llong-max-or-lower-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!