C Quirk??

John Peters jsp at sp7040.UUCP
Wed Feb 10 11:02:13 AEST 1988


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.  Maybe someone out there
> can shed some light on the subject...
> 
> #include <stdio.h>
> #include <ctype.h>
> 
> main()
> {
>   char ch;
> 
>   puts("Enter a Character:  ");
> 
>   while( (ch = getchar()) )
>   {
>     if( isupper(ch) )
>       tolower(ch);
> 
>     printf("%c\n", ch);
>     puts("Enter a Character:  ");
>   }
> }
> 
> Here's the output that I get when running the above program:
> 
> Enter a Character:
> a
> A
> Enter a Character:
> 
> 
> Enter a Character:
> 
> 
> The first time, everything is ok.  The next time, however, it seems
> to just blow right by the getchar().
> 

This does indead leave the newline in the buffer.  I no of several ways to
get around the problem.  Probabley the easiest (and it can also save a lot
of other hastles) is:

#include <stdio.h>
#include <ctype.h>

#define EVER (;;)

main()
{
    char	a[5];

    for EVER {
	gets (a);
	printf ("%c\n", toupper (a[0]));
    }
}

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

Also you can use the standard scanf botch to do it.

	scanf ("%c%*c", a);  

This tells the program to skip the next character after reading one.

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.

					--  John  --

	{backbones}!ihnp4!utah-cs!utah-gr!uplherc!sp7040!jsp

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



More information about the Comp.lang.c mailing list