Yes, you can check for overflow of numbers read from input, but scanf
is not the way to do it. Calling scanf("%d", &n)
when the input number is too big to be represented as an int
actually has undefined behavior. (IMHO this is very unfortunate, and makes scanf
nearly impossible to use safely for numeric input.)
But the strto*
functions:
strtol
(for long
)
strtoll
(for long long
)
strtoul
(for unsigned long
)
strtoull
(for unsigned long long
)
strtof
(for float
)
strtod
(for double
)
strtold
(for long double
)
though they're a bit more difficult to use, have well defined behavior for all inputs.
Use fgets
to read a line of input, then use one of the strto*
functions to convert the input to a number of the appropriate type.
On overflow, these functions return the minimum or maximum value of the appropriate type and set errno
to ERANGE
. You should set errno
to 0
before the call. (Checking errno
setting lets you distinguish between an overflow and an actual input of, say, 2147483647
.)
Read the man documentation for the appropriate function for the gory details.
Since there's no strtoi
function for int
, you can use strtol
, check whether the input was a valid long
, and then check whether the long
value is in the range INT_MIN
.. INT_MAX
; similarly for unsigned int
and strtoul
.