From: Simon Harris Newsgroups: comp.os.msdos.djgpp Subject: Re: Why don't printf work properly with getch ()? Date: Wed, 08 Oct 1997 16:36:31 +0100 Organization: Imperial College Lines: 84 Message-ID: <343BA87F.1A3B@ic.ac.uk> References: <01bcd38e$b9e2da40$0b0867d1 AT default> <19971008135201 DOT JAA16622 AT ladder02 DOT news DOT aol DOT com> Reply-To: s DOT j DOT harris AT ic DOT ac DOT uk NNTP-Posting-Host: linpc.me.ic.ac.uk 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 Br5an wrote: > > Newbie wrote: > > >I had some problem with printf and getch working together. > >Seems to me that the last printf preceeding a getch is executed > >only after a > key is pressed. > > >examples: > > printf ("\n1"); > > printf ("\n2"); > > printf ("\n3"); > > getch (); > >would produce > >1 > >2 > >waiting for keystroke, after a key is pressed > >3 > > Another wrote: > > >This is because they're not designed to. printf is a stdio library > >function, and getch is a conio library function. They're not > >designed to be used together. > > >You should be using all-stdio or all-conio functions to do your job. > >That means either using printf and getchar, or cprintf and getch, > >respectively. > > This may all be true. With other compilers I've shamelessly mixed stdio > and conio functions without a hitch. But in the example above, could it just > be another example of buffered output most of us here (at msdos.djgpp) have > read so much about lately? > > Sincerely, Br5an AT aol DOT com Exactly, the last 3 to be printed is buffered until the end of program (in the case of DJGPP - whether an non-new-lined string pending at the end of a program is printed is apparently up to the system) or the next new-line. Should you want to print something with printf() and then receive input using getch(), on the same line, you can use fflush() to finish writing the last printf(), e.g. printf("Do you want to continue?\n"); printf("Reply Y/N ->"); reply=getch(); results in Do you want to continue? [user types key] Reply Y/N -> but printf("Do you want to continue?\n"); printf("Reply Y/N ->"); fflush(stdout); reply=getch(); results in Do you want to continue? Reply Y/N -> [user types key] Another example of how things go wrong! #include #include int main() { printf("Press a key to clear the screen"); getch(); clrscr(); return 0; } Again, fix with fflush(stdout) after the printf(). Simon.