0

I wrote the following program:

#include <cstdio>
#include <ctime>
int main()

{
time_t t;
int d;
printf("\nHello 1");    
    time(&t);           
    d=t;
    while (t-d<3) /*wait 3 seconds*/
    {
        time(&t);
    }
printf("\nHello 2");
    time(&t);
    d=t;
    while (t-d<3)  /*wait 3 seconds*/
    {
        time(&t);
    }
printf("\nHello 3");
return 0;
}

after build the program, i run it. The program waits 3 seconds to show the line "Hello 1".

why is it written first but executed later?

Lundin
  • 195,001
  • 40
  • 254
  • 396

2 Answers2

0

On some OS, the output buffer stdout typically needs to be "flushed" in order to make what you print there appear on screen. The \n acts as a "flush" and that explains the behavior.

You can fix this by adding a fflush(stdout); call after each printf. This forces a screen update. Alternatively move the \n to the end of each line instead of at the beginning.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

Basically, you need to flush the buffer. So the simplest thing is to move from this: printf("\nHello 1"); to printf("Hello 1\n");

Try this https://onlinegdb.com/u5L2xtwgf

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34