delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/21/07:06:00

Date: Tue, 21 Oct 1997 13:04:18 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
To: "John M. Aldrich" <fighteer AT cs DOT com>
cc: djgpp AT delorie DOT com
Subject: Re: Scanf function
In-Reply-To: <344BA86D.58F@cs.com>
Message-ID: <Pine.SUN.3.91.971021130337.3667D-100000@is>
MIME-Version: 1.0

On Mon, 20 Oct 1997, John M. Aldrich wrote:

> Marsel wrote:
> > 
> > #include <stdio.h>
> > main()
> > {
> >  char c;
> >  int n;
> >  printf("Write an integer: ");
> >  scanf("%d",&n);
> >  printf("Write a character: ");
> >  scanf("%c",&c);
> >  printf ("The integer is: %d and the character is: %d \n",n,c);
> >  }
> > 
> > Why the secong scanf function does not wait until the caracter is
> > introduced? the c variable always contain the caracter \010
> >  I know it will be better to use c=getch(); but why the this code does not
> > work well ?
> 
> Because you have never bothered to read your C textbook thoroughly. 
> scanf() normally ignores whitespace in the input it parses, but "%c"
> makes scanf() return the first character it reads, regardless of whether
> it is whitespace or not.

John's analysis is very accurate.  Therefore, a simple solution is to
change the format of the second `scanf', so it does skip whitespace:

  printf("Write a character: ");
  scanf(" %c",&c);

This will miraculously work!

Personally, I always precede format specifiers with at least one
space.  I find it much more robust than relying on whitespace-skipping
behavior of certain format letters.  My experience is that programs
don't usually need to read whitespace, especially when human input is
involved.  So I suggest to always use leading whitespace in `scanf'
formats, especially if you are a newcomer to C and aren't too familiar
with formatted I/O pitfalls.

- Raw text -


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