Reputation: 33
while(1) {
printf("Hello World");
}
We know this would keep on printing the Hello World string for infinite times. My goal is to print this for 10 seconds. I tried this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int ticks = clock();
while(ticks <= 10000000000) {
printf("Hello World\n");
}
return 0;
}
It still goes for an infinite time. Please let me where did I made the mistake.
Upvotes: 0
Views: 970
Reputation: 12698
This code will print the string, then issue a '\r'
to return the cursor to the left of the terminal, then issue a "\033[K"
to erase from the cursor to the end of the line, and a '\n'
to end the program on a new line (you can avoid this, as the cursor is already in an empty line)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("Hello, world ");
fflush(stdout); /* force a write(2) to output the string to the terminal */
sleep(10);
printf("\r\033[K\n"); /* carry return, escape to erase from the
* cursor to the end of the screen, and new
* line */
return 0;
}
Upvotes: 0
Reputation: 117443
I mainly just want to print for like 10 seconds
Then I suggest using the standard time()
function.
#include <stdio.h>
#include <time.h>
int main() {
time_t end_time = time(NULL) + 10; // calculate the end time
while(time(NULL) < end_time) { // loop until the end time is reached
printf("Hello World\n");
}
}
Upvotes: 2
Reputation: 44329
Maybe use time()
Save the start time in one variable. Have another variable with the current time and keep printing until the difference is what you want.
Like
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void) {
time_t start = time(NULL); // Get start time
time_t current = start;
while(current - start < 10) { // Check difference
printf("Hello World\n");
// sleep(1); // To limit amount of output if needed
current = time(NULL); // Update current time
}
return 0;
}
Upvotes: 1