K
Keith Thompson
Richard Heathfield said:Keith Thompson said:
For one thing, its behavior on numeric input overflow is undefined.
But you can use field width specifiers to prevent this. See, for instance,
the C89 example of fscanf (which is obviously analogous to sscanf):
++++++++++++++++++++++
fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name);
with input:
56789 0123 56a72
will assign to i the value 56
++++++++++++++++++++++
True, but it's not a very flexible way to handle it. If INT_MAX is
32767, for example, then you can use "%4d" to safely limit input
values to 9999, but if you want to handle values from 10000 to 32767
you can't avoid UB if the user enters something from 32768 to 99999.
It would have been really nice if the standard had required sane
behavior.
Note that the example invokes UB if the input for "%f" overflows.
Not that I'm rootin' for *scanf or anything. But of the *scanf family,
sscanf is certainly the least useless, and it seems to me that it makes no
odds whether the string on which it works comes from an "interactive"
source or not.
Agreed, numeric overflow reading from a file isn't much less of a
problem than numeric overflow reading from a keyboard. You *might*
have better control over file input, but a robust program should
handle bad input even if you're sure it can't happen.