0
for(j = 1; j < 11; j++)
        {
            printf("%ds ",j);
            sleep(1);
        }

i have expected that this code will print "1s 2s 3s ... 10s" where there is 1 second interval between them but instead it prints all the numbers after 10 seconds. how should i fix it? i'm working on ubuntu.

Swaff
  • 13,038
  • 4
  • 22
  • 26
mkeremkeskin
  • 644
  • 9
  • 23

2 Answers2

2

The stdout stream is buffered, so if you immediately want your results you need to flush that buffer with fflush():

for (j = 1; j < 11; j++) {
    printf("%ds ", j);
    fflush(stdout);
    sleep(1);
}
orlp
  • 98,226
  • 29
  • 187
  • 285
0

add a \n to your printf to flush.

for(j = 1; j < 11; j++)
        {
            printf("%ds\n",j);
            sleep(1);
        }

For more info, see here.

Community
  • 1
  • 1
NKCSS
  • 2,641
  • 1
  • 19
  • 37
  • Incorrect. Newlines are not required to flush the stdout buffer and more importantly will break the original asker's format. – orlp Apr 07 '11 at 19:33
  • It was just a suggestion; I posted the link to a previous question that talks all about fflush() and disabling the buffer. Let's not rehash it all here, let him read the original question. – NKCSS Apr 07 '11 at 19:34
  • Let's not rehash it all here? You suggested something completely irrelevant: newlines. Only one part of your answer was useful, an other question. – orlp Apr 07 '11 at 19:36
  • @nightcracker: I might not have formulated it in the best possible way, but what I tried to say was that it didn't print till the end because the buffer wasn't flushed, something that printf automatically does when you put a newline character into your print string. – NKCSS Apr 07 '11 at 19:43
  • although only when printing to a terminal. – Neil Apr 07 '11 at 19:57