ctimeline

Is it possible to wait a few seconds before printing a new line in C?


For example could I make it type something like

"Hello"
"This"
"Is"
"A"
"Test"

With 1 second intervals in-between each new line?

Thanks,


Solution

  • Well the sleep() function does it, there are several ways to use it;

    On linux:

    #include <stdio.h>
    #include <unistd.h> // notice this! you need it!
    
    int main(){
        printf("Hello,");
        sleep(5); // format is sleep(x); where x is # of seconds.
        printf("World");
        return 0;
    }
    

    And on windows you can use either dos.h or windows.h like this:

    #include <stdio.h>
    #include <windows.h> // notice this! you need it! (windows)
    
    int main(){
        printf("Hello,");
        Sleep(5); // format is Sleep(x); where x is # of milliseconds.
        printf("World");
        return 0;
    }
    

    or you can use dos.h for linux style sleep like so:

    #include <stdio.h>
    #include <dos.h> // notice this! you need it! (windows)
    
    int main(){
        printf("Hello,");
        sleep(5); // format is sleep(x); where x is # of seconds.
        printf("World");
        return 0;
    }
    

    And that is how you sleep in C on both windows and linux! For windows both methods should work. Just change the argument for # of seconds to what you need, and insert wherever you need a pause, like after the printf as I did. Also, Note: when using windows.h, please remember the capital S in sleep, and also thats its milliseconds! (Thanks to Chris for pointing that out)