getline - sort of

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

Richard Heathfield

Keith Thompson said:

[sscanf]
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.

Yes you can, by capturing it as a long int. (But your argument scales to
long int, of course.)
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.

Typical. (They should have written %3f.)

<snip>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top