问题
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()
returnsLONG_MIN
. If an overflow occurs,strtol()
returnsLONG_MAX
. In both cases,errno
is set toERANGE
. Precisely the same holds forstrtoll()
(withLLONG_MIN
andLLONG_MAX
instead ofLONG_MIN
andLONG_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), anderrno
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