www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/03/26/21:16:34

Message-ID: <3ABFAFE1.D18CDF9@acm.org>
From: Eric Sosman <esosman AT acm DOT org>
X-Mailer: Mozilla 4.72 [en] (Win95; U)
X-Accept-Language: en
MIME-Version: 1.0
Newsgroups: comp.os.msdos.djgpp
Subject: Re: is this a bug?
References: <99oo0k$gr7$1 AT neptunium DOT btinternet DOT com>
Lines: 54
Date: Tue, 27 Mar 2001 02:06:35 GMT
NNTP-Posting-Host: 12.78.244.139
X-Complaints-To: abuse AT worldnet DOT att DOT net
X-Trace: bgtnsc04-news.ops.worldnet.att.net 985658795 12.78.244.139 (Tue, 27 Mar 2001 02:06:35 GMT)
NNTP-Posting-Date: Tue, 27 Mar 2001 02:06:35 GMT
Organization: AT&T Worldnet
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Michael Ahumibe wrote:
> 
> Hi
> 
> The following program should ask for a character to be input near the end
> 
> #include <stdio.h>
> 
> int main()
> {
>  char string[20];
>  unsigned int number;
>  char test;
> 
>  printf("Enter a string: ");
>  scanf("%s", &string);
> 
>  printf("Enter a number: ");
>  scanf("%u", &number);
> 
>  printf("Enter a character: ");
>  scanf("%c", &test);
> 
>  printf("%s %u %c",string,number,test);
> 
>  return 0;
> }
> 
> I compile the code and run it. The line containing scanf("%c", &test); is
> skipt!! can someone tell me the exact reason for this?

    The scanf("%u",...) call converts a number, which consists
of a string of digits.  Where does the string end?  At the first
non-digit character, which is probably an '\n' corresponding to
the ENTER you typed after the numeric string.  scanf() inspects
this '\n', decides it is not a digit, and pushes it back on the
input stream; the '\n' is not consumed by the "%u" conversion.

    Then along comes the scanf("%c",...) call.  "%c" will accept
any character at all, so it consumes the '\n' which is already
sitting on the input stream.

    scanf() looks fairly simple, but can actually be quite tricky
to use well.  Many experts suggest using fgets() to read a line
into an array and then using sscanf() to convert the line's stored
characters; surprises like the one you've encountered are less
likely with this approach.

    See also the comp.lang.c Frequently Asked Questions list at
(I don't have the entire URL handy at the moment) www.eskimo.com.

-- 
Eric Sosman
esosman AT acm DOT org

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019