But how can I avoid [various problems with scanf]?
[/QUOTE][/QUOTE]
Not in general. Maybe in some specific, well-controlled cases.
For example:
do {
int k = scanf("%d", &n);
switch (k) {
[snippage]
As someone (I think Keith Thompson) pointed out, this can misbehave
(formally, has "undefined behavior") if someone enters an overlarge
number. Your second variant (using %ld and a "long") still suffers
from this problem. (In practice, real implementations almost always
do at least one of these things: use strtol() internally, thus
clamping out of range inputs; use atoi() or atol() internally,
often behaving annoyingly but predictably by "wrapping" out of
range inputs based on the machine's internal representation; or
discover -- in some cases based solely on input length, and thus
sometimes having trouble with leading zeros -- that the value would
have been out of range, and stop the scanf engine with a matching
failure.)
More practically, this code is rather "user-unfriendly" when the
scanf() occurs after a recent prompt:
printf("enter a number: ");
fflush(stdout);
/* your loop using scanf() here */
If the user types nothing but a carriage return, the computer
simply sits there, having accepted the input line, waiting for
more input -- but without producing any diagnostic output like:
puts("Please enter an integer");
or repeating the prompt or anything. The scanf() call is still
running, waiting for more input, since "%d" skips leading white
space, and an empty line is "white space".
The rule that beginners should never use scanf() is, I think, a
good one. (To gain experience with the scanf family's behavior,
one can get input lines into buffers and apply sscanf(), then
inspect the subsequent wreckage. The buffers preserve the original
input and help insulate the program's "weird internal behavior due
to scanf" from its "obvious and immediate external I/O behavior".
In other words, the buffers ... well, they *buffer*:
buffer ... [as transitive verb] ... 12. to cushion, shield,
or protect. 13. to lessen the adverse effect of ...
-- from <
http://dictionary.reference.com/browse/buffer>
The scanf() function is a lot like a field of cactus in bloom:
pretty, but it is dangerous to get too close.
)