Mail Archives: djgpp/1997/10/21/07:06:00
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 -