From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: Scanf function Date: Mon, 20 Oct 1997 18:52:29 +0000 Organization: Two pounds of chaos and a pinch of salt Lines: 56 Message-ID: <344BA86D.58F@cs.com> References: <62fp85$nq4$1 AT power DOT ci DOT uv DOT es> Reply-To: fighteer AT cs DOT com NNTP-Posting-Host: ppp226.cs.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk 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. The first scanf() statement reads an integer, leaving the newline ('\n') in the input buffer. The second scanf() looks in the buffer, reads the newline, and returns it, without asking you for more input. You have a couple of solutions: - flush the buffer after the first scanf() with "fflush( stdout );" (this is ugly) - read in an extra character to get rid of the blank space. (this fails if more than one extra character is the buffer) - use a loop to read until you encounter a newline: while( getchar() != '\n' ) ; (this is the most commonly used method, IMHO) - substitute getch() for the second scanf(). !!! WARNING !!! getch() is a conio function, not a stdio function. Under DJGPP stdio functions are line buffered and so you won't see the output from the second printf() until after you read the character. This is not a bug but a feature of DJGPP, and you can learn more about it in chapter 9.4 of the DJGPP FAQ (v2/faq210b.zip from SimTel or online at http://www.delorie.com/djgpp/v2faq/). hth -- --------------------------------------------------------------------- | John M. Aldrich | "Sin lies only in hurting other | | aka Fighteer I | people unnecessarily. All other | | mailto:fighteer AT cs DOT com | 'sins' are invented nonsense." | | http://www.cs.com/fighteer | - Lazarus Long | ---------------------------------------------------------------------