0

I want to print a line and then get it erased after ten seconds. So I thought that I should write a timer as a preliminary programme and with erasure I could deal later using whatever I find on the internet (using \r for example). And so I want to print "I love nachos" and ten seconds later "I hate nachos". However, even though printf("I love nachos") is written before any conditions, the programme prints both strings after ten seconds.

#include <stdio.h>
#include <time.h>
int main(void) {
  printf("I love nachos");
  time_t now = time(NULL);
  while (1)
  {
  time_t future = time(NULL);
    if ((future-now)==10)
      {
       break;
      }
  }
  printf("I hate nachos");
  return 0;
}

I asked my friend to tackle the problem and he wrote:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    printf("Start\n");

    time_t t0 = time(NULL);

    while ( (difftime(time(NULL), t0)) <= 10.0 )
    {}

    printf("End");

    return 0;
}

However, in that case the programme only works with \n in printf("Start\n"). If I remove \n I get the same result as per my initial code and I obviously don't want \n there, because I wouldn't be able to erase the line with \r

  • Instead of busy waiting in a loop I suggest to use a function like `sleep`/`nanosleep` (POSIX) or `Sleep` (Windows) – Bodo Mar 11 '21 at 12:50

1 Answers1

0

The printf output to stdout is by default line buffered. That means nothing is actually sent out until either the internal buffer is full or a newline is added or the FILE is closed (as happens implicitly when the program exits)

So either add a newline or use fflush to force the buffer to be transmitted immediately to the output.

koder
  • 1,585
  • 2
  • 8