Sawy3r
Sawy3r

Reputation: 83

How do I implement the sleep function in my for loop correctly? (Ubuntu)

I'm trying to make my code print something to the screen, then wait 1 second, then go around the for loop and print it again 21 times. It works when I do this in Windows in CodeBlocks by using #include and then Sleep(1000). But when I'm doing it on my Ubuntu VM by using #include and sleep(1), everything disappears from my terminal for 21 seconds then all appears at once. I think I'm using the wrong function or something.

Any ideas?

This is the code in Ubuntu terminal which ends up removing everything already on my terminal, waits 21 seconds then just prints "Hello" 21 times.

#include <stdio.h>
#include <unistd.h>

int main()

{
    for (int i = 0; i < 21; i++)
    {
        printf("Hello");
        sleep(1);           
    }

}

This is the code in Windows which prints "Hello" every second for 21 seconds therefore printing 21 Hello's on my screen over 21 seconds. Which is what I'm trying to achieve in my Ubuntu VM.

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

    int main() {
        for (int i = 0; i < 21; i++)
        {
            printf("Hello");
            Sleep(1000);
        }

        return 0; 
    }

Upvotes: 2

Views: 119

Answers (2)

SergeyA
SergeyA

Reputation: 62583

printf output is buffered - which means, it is not guaranteed to appear on the screen immediately. Rather, it appears when one of the following happens:

  • when the buffer becomes full, - at which time the old contents of buffer is displayed to the screen and the buffer is cleared fresh for the new output - this is called buffer flushing
  • when the application terminates - which forces flushing of all the printf buffers, and this is what you see on the screen
  • When buffer is flushed by the programmer.

The last case is most interesting for you, and there are two ways you can do this - either include \n (new line) control character in your string, like

 printf("Hello\n");

or call fflush for stdout stream, like

 printf("Hello");
 fflush(stdout);

Upvotes: 1

BadZen
BadZen

Reputation: 4265

In UNIX, process streams buffer - they accumulate I/O and do not "flush" to the underlying device immediately on write, per default. So - you need to flush the stream:

#include <stdio.h>
#include <unistd.h>

int main()

{
    for (int i = 0; i < 21; i++)
    {
        printf("Hello");
        fflush(stdout);
        sleep(1);           
    }

}

It would also work if you output a newline '\n' after "Hello", I believe.

Upvotes: 1

Related Questions