user2638180 user2638180 - 1 year ago 88
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

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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download