user2638180
user2638180

Reputation: 1023

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.

Upvotes: 2

Views: 245

Answers (2)

Andrew Henle
Andrew Henle

Reputation: 1

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 */
   ...
}

Upvotes: 2

dbush
dbush

Reputation: 224112

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

Upvotes: 5

Related Questions