user2638180 user2638180 - 1 month ago 8
C Question

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

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.

Answer

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