What's so bad about scanf anyway???
Stanley Friesen
sarima at tdatirv.UUCP
Tue Nov 13 03:30:35 AEST 1990
In article <16582 at netcom.UUCP> avery at netcom.UUCP (Avery Colter) writes:
>In the self-teaching course I have here, scanf is the most often used
>input function. I don't see gets used much at all.
Sounds like a poorly designed course. using scanf for user input is very
dangerous. Why? Because scanf keeps reading until its entire input list
is fulfilled or EOF is reached. It treats NL as *white* *space*.
Thus given the invocation:
scanf("%d %d %d", &i, &j, &k);
a user can become very frustrated if he only types in two integers, followed
by a NL (or RETURN). The computer will just *sit* there and do nothing.
No error message about incomplete input, no prompt, no output, no nothing.
And unless the poor user can intuit that the computer wants another number,
he is stuck. Bleah.
>And indeed, gets only seems of much advantage when you want to take in
>a whole line into one string.
Or if you want to make sure that the computer can respond to the user after
every input line.
>Otherwise, scanf can take individual numbers and put them directly into
>numerical variables. With gets, you'd have to first manually parse the
>line, and then use strtol to translate them into numbers.
Hardly, you just use sscanf on the string read by gets. Since sscanf treats
end-of-string as EOF, this will not get stuck like scanf. Now, if sscanf
returns an input count lower than expected you can print a "Usage:" message
to the user explaining clearly that you need that third number. Voila,
much less frustration, and a more friendly, conversational program.
>I didn't see puts used for printing strings to screen much either.
>printf was the function of choice.
Agreed here. There is little reason to use puts unless the output string
is already formatted.
--
---------------
uunet!tdatirv!sarima (Stanley Friesen)
More information about the Comp.lang.c
mailing list