`Extra' newline when using getchar() (was: C Quirk??)

der Mouse mouse at mcgill-vision.UUCP
Mon Mar 7 15:38:07 AEST 1988


In article <285 at sp7040.UUCP>, jsp at sp7040.UUCP (John Peters) writes:
> In article <1653 at ssc-vax.UUCP>, dmg at ssc-vax.UUCP (David Geary) writes:
>> I've been wondering about this for a long time.
>> [code that uses getchar() to read characters]
>> [David is puzzled about the extra newline at the end of a line]
> This does indead leave the newline in the buffer.

Quite so.

> [recommends a method involving]
>     char	a[5];
> [...]
> 	gets (a);

> This gets ride of certain other evils such as accidentally entering
> more than one character.

Except that if you enter more than four characters, it breaks badly.
(It overwrites whatever happens to lie past a[].)  If you must use
gets-type routines, you should always use fgets(), to which you pass
the length of the buffer, so it can avoid overflowing it.

> Since it sounds like you are wanting just one character at a time how
> about considering putting the system in raw mode so that when you do
> the getchar it comes right back at you.  Why wait an force the user
> to hit a charrage return.

Cbreak mode is probably better than raw mode.  Have you ever written a
program that uses raw mode and then discovered a bug in the handling of
the command that's supposed to get you out?  Great fun, isn't it?

> 	DISCLAIMER:  My spelling is my own and boy does the company hate it!

I can see why.

					der Mouse

			uucp: mouse at mcgill-vision.uucp
			arpa: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list