Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!pasteur!ucbvax!decwrl!labrea!bloom-beacon!athena.mit.edu!peter From: peter@athena.mit.edu (Peter J Desnoyers) Newsgroups: comp.lang.c Subject: Re: single character input Message-ID: <5455@bloom-beacon.MIT.EDU> Date: 20 May 88 13:49:26 GMT References: <3423@drivax.UUCP> Sender: daemon@bloom-beacon.MIT.EDU Reply-To: peter@athena.mit.edu (Peter J Desnoyers) Distribution: na Organization: Massachusetts Institute of Technology Lines: 42 In article <3423@drivax.UUCP> braun@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@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.