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,

1

4 Answers

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)

2

something not as elegant as sleep(), but uses the standard library:

/* data declaration */ time_t start, end; /* ... */ /* wait 2.5 seconds */ time(&start); do time(&end); while(difftime(end, start) <= 2.5); 

I'll leave for you the finding out the right header (#include) for time_t, time() and difftime(), and what they mean. It's part of the fun. :-)

2

You can look at sleep() which suspends the thread for the specified seconds.

0

Works on all OS

int main() { char* sent[5] ={"Hello ", "this ", "is ", "a ", "test."}; int i =0; while( i < 5 ) { printf("%s", sent[i] ); int c =0, i++; while( c++ < 1000000 ); // you can use sleep but for this you dont need #import } return 0; } 
9

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like