C Quirk??

Caesar's Palace morning glory, silly human race. greywolf at unicom.UUCP
Tue Feb 16 18:22:40 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 is what I think:
# 
# It asks me to "Enter a Character:  ".  I type 'a', and then a newline.
# getchar() grabs the 'a' from stdin, but leaves the newline hanging.
# The next time getchar() comes around, it grabs the newline that was
# left hanging around last time.
# 
# Note that if I insert fflush(stdin) before I do if( isupper(ch) ),
# everything works correctly.
# 
# Is this a *bug* in C, or is it a *feature*.  Am I interpreting events
# correctly?  Is there a fix besides fflush()?
# 
# I love to program in C, but this p*sses me off.  Thanks in advance
# for the replies.

Have you tried inserting the following:

*** what_was_here ***
--- my_additions ---

*** if( isupper(ch) )
***   tolower(ch);
*** printf("%c\n", ch);
--- while (getchar() != '\n')
---	;
*** puts("Enter a Character: ");
*** }
...

That oughtta work, given it's expecting the newline after a character is
entered anyway.  If you want to interpret newlines as well, you're going to
have to settle for cbreak or raw mode for input.


Hope that helped,

Roan.

-- 
 " <- (2 dots)		    ::   / | \ ...!{sun,ucbvax}!pixar!unicom!greywolf
Roan Anderson, Local Guru   ::  :  |  :
(which doesn't say much)    ::  : /|\ : war: Invalid argument.
:::::::::::::::::::::::::::::::: =_|_=  ::::::::::::::::::::::::::::::::::::::



More information about the Comp.lang.c mailing list