Date: Tue, 21 Oct 1997 13:04:18 +0200 (IST) From: Eli Zaretskii To: "John M. Aldrich" cc: djgpp AT delorie DOT com Subject: Re: Scanf function In-Reply-To: <344BA86D.58F@cs.com> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Precedence: bulk On Mon, 20 Oct 1997, John M. Aldrich wrote: > Marsel wrote: > > > > #include > > 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.