single character input
Peter J Desnoyers
peter at athena.mit.edu
Fri May 20 23:49:26 AEST 1988
In article <3423 at drivax.UUCP> braun at drivax.UUCP (Kral) writes:
>... what I consider to be rather odd
>behaviour on the part of scanf. For instance, if I do the following:
> char c ;
> puts(prompt) ;
> scanf("%c ", c) ;
> switch(c) {
> ... }
>The program ends up reading one line behind what is input; in other words, I
>have to enter something (anything!) the first time, then the second line
>entered triggers the program reading the first line, etc. Not at all what I
>expected, and it seems not too useful to me. I got so hung up on scanf that
>I couldn't think of anything else. I wonder why scanf does this? Am I missing
>something equally obvious here?
Someone here made the mistake of changing one of the intro programming
courses at MIT from pascal (I think) to C, and at least one person I know
got caught by this same bug. They wrote:
for (...) { printf( "y/n:"); scanf( "%c", &answer); ...}
Unfortunately, what they got was:
value read: input typed:
'y' 'y\n' (note - scanf will not return until
'\n' nothing you hit return)
and so forth. Since they were testing only against 'y', they never noticed
that the non-y value wasn't a 'n', and got seriously confused.
Moral - the interaction of character-at-a-time reads through scanf or
whatever and buffered IO in the TTY driver is non-intuitive. Remember
that you are going to get every character typed at the program, but a
line at a time.
Peter Desnoyers
peter at athena.mit.edu
Please, no flames about C not being appropriate to an intro programming
course. (It was 1.00 or 2.10 - taught by either civ. e. or mech. e.)
You don't have a good idea of how the computer (not the language, the
computer) works until the end of a course - C requires this knowledge
in the beginning. Besides, if you know {C, Pascal} you know {Pascal, C}.
They're all Algol derivatives, anyway.
More information about the Comp.lang.c
mailing list