From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: PLEASEHELPgetchar Date: Sun, 02 Nov 1997 11:40:59 +0000 Organization: Two pounds of chaos and a pinch of salt Lines: 59 Message-ID: <345C66CB.70D6@cs.com> References: <01bce705$d5229f40$12d01ace AT pjestess> Reply-To: fighteer AT cs DOT com NNTP-Posting-Host: ppp229.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 John Estess wrote: > > In an example, the DJGPP compiler blazes right through these three lines > without yn picking up the input value. I know this because I inserted a > print statement right after the second line and after the third (curious). > I also tried the getche fuction with the conio.h library, but it acted the > same. Since getche was supposed to be an unbuffered function, I was less > than impressed. The program worked under C++ Builder (trial edition), but I > really want to use DJGPP and I'm more than a little miffed that I can't > even input a single charactor. How is it done? According to the "Joy of C" > and the reference book for PowerC, this should work. Hell, it was given to > us as an example of how to do it! WAAAAAHHHH! > > Please cc to my email - my news server bites. > > printf ("\n Toss again? (Y/N)") ; /*prompt */ > yn = getchar() ; > fflush (stdin) ; fflush() is not defined by ANSI to work on input streams. This is an illegal construct that's somehow snuck its way into Borland and other so-called "standard" DOS compilers. To be precise, when you type a character and press Enter, two characters are inserted into the input buffer: the char you typed and the CR character. getchar() reads the first character, and the next time it is called, it reads the second (the CR) without waiting for you to type anything. This is standard C stuff here. Your book probably tells you to use fflush( stdin ) because it's based on those nonstandard compilers. Alternatives: 1) while ( getchar() != '\n' ) ; 2) char buf[256]; /* ... */ fgets( buf, 256, stdin ); yn = buf[0]; 3) #include yn = getche(); If you pick number 3, be careful mixing conio functions with stdio functions; they work separately. hth P.S.: I recommend The Waite Group's _New C Primer Plus, 2nd edition_, because it doesn't gloss over these little details. It teaches correct ANSI C. -- --------------------------------------------------------------------- | John M. Aldrich | "Courage is the complement of fear. | | aka Fighteer I | A man who is fearless cannot be | | mailto:fighteer AT cs DOT com | courageous. (He is also a fool.)" | | http://www.cs.com/fighteer | - Lazarus Long | ---------------------------------------------------------------------