single character input

Dave Burton daveb at laidbak.UUCP
Fri May 27 00:30:26 AEST 1988


In article <3443 at drivax.UUCP> braun at drivax.UUCP (Kral) writes:
|In Article <6151 at sigi.Colorado.EDU>, swarbric at tramp.Colorado.EDU (Frank 
|Swarbrick), says:
|:I must have missed something along the line somewhere.  ch = getchar() works
|:fine for me.  I can use backspace to edit it.  I can type as many characters as
|:I want.  When I finally press return the first character that is left is
|:assigned to ch.
|The problem is this: if the first character input is not a valid input, what do
|you do?  You loop back, redisplay the prompt (probably with some sort of error
|message along the way) and read again.  What you will get is the next character
|input on the old line, which will probably also be wrong, and the process will
|continue until all of the character have been read.  The result is a bunch of
|error messages displayed because the user entered one bad input line.

Just flush the rest of the line with a gets().
If you really need punctual response, and control over how many characters
the user can type before [RETURN], you'll need to use a so-called raw mode,
(or at least set CBREAK if using UNIX).

#include <stdio.h>
main()
{
	int c;
	char buf[80];

	printf("yes or no: ");
	while ((c = getchar()) != 'y' && c != EOF) {
		gets(buf);
		printf("try again.\n");
		printf("yes or no: ");
	}
	printf("done.\n");
}



More information about the Comp.lang.c mailing list