For example could I make it type something like
"Hello" "This" "Is" "A" "Test"
With 1 second intervals in-between each new line?
Thanks,
How do you make a C program pause for a few seconds? Insert, wherever you need your program to make a delay: sleep(1000); Change the "1000" to the number of milliseconds you want to wait (for example, if you want to make a 2 second delay, replace it with "2000".
The newlinelineIn computing, a line is a unit of organization for text files. A line consists of a sequence of zero or more characters, usually displayed within a single horizontal sequence.https://en.wikipedia.org › wiki › Line_(text_file)Line (text file) - Wikipedia character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
sleep() function in C allows the users to wait for a current thread for a specific time. Other operations of the CPU will function properly but the sleep() function will sleep the present executable for the specified time by the thread.
The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string.
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)
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With