Reputation: 63
I'm trying to print each character separately and have a delay between them, so when I run the loop, instead of each character printing immediately it prints one character at a time.
The goal is to have a string that would be printed out one letter at a time and it would look like it is being typed out by the program.
I used a code for the delay that I found on the internet at it is supposed to make a time delay between the printing of the characters.
#include <stdlib.h>
#include <time.h>
#include <string.h>
void delay(unsigned int milliseconds) {
clock_t start = clock();
while ((clock() - start) * 1000 / CLOCKS_PER_SEC < milliseconds);
}
int main() {
int c = 0;
char s[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
for (c = 0; s[c] != '\0'; c++) {
printf("%c", s[c]);
delay(1000);
}
return 0;
}
I expected for it to be printed every letter at a time with a second delay between each letter, but instead it waits 6 seconds and prints everything out.
Upvotes: 4
Views: 2226
Reputation: 21562
Output from printf
and other functions that write to stdout
and other files may be buffered, so they may appear to print only when the buffer is flushed.
You can add the line fflush(stdout)
inside your loop to force the buffer to be flushed to the stream, guaranteeing that any pending output currently in the buffer will be written out.
Upvotes: 4