Mail Archives: djgpp/1997/10/08/13:02:36
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 <stdio.h>
#include <conio.h>
int main()
{
printf("Press a key to clear the screen");
getch();
clrscr();
return 0;
}
Again, fix with fflush(stdout) after the printf().
Simon.
- Raw text -