K
Keith Thompson
Malcolm McLean said:Normally the valid numbers for the application are much lower than
INT_MAX, so the %5d method works for most situations.
When talking about something as generic as reading a number
from stdin, I don't know what "normally" is supposed to mean.
Some applications might only want numbers below 100; others might
need to handle anything in the range of int. If you're writing
a library routine to read integers, restricting the input to an
arbitrary range is not a good idea.
Furthermore, if you call scanf("%5d", &n) and enter "123456", n is
set to 12345 and the 6 is left in the input stream. You could add
code to check for that, but then you might as well use strtol().
I checked my version of sscanf, and it sets the target to 0xFFFFFFFFF
(all bits set) and returns 1 on begin fed a massive integer. That's
undesirable, because it should be returning 0 and setting the stream
to the start position. Sometimes you just want to skip a number and
parse the following text, in which case my compiler's behaviour is
best, but if the value is used, the program will get into an odd
state, even if checks are made.
I'm not at all sure what sscanf() *should* do for an out-of-range
numeric input. The trouble is that it just returns the number
of items matched; it has no good way to distinguish between
syntactically bad input and an out-of-range number.
If the behavior were to be defined in a future standard, it could
either treat it as a matching failure, or it could set the object to,
say, INT_MIN or INT_MAX and set error to ERANGE, like strtol() does.
Either would be better than leaving the behavior undefined.
(Incidentally, it's your runtime library, not your compiler, that
implements sscanf.)