I have a somewhat stupid problem because it’s supposed to be utterly simple …
Assume I have string:
char *str = "stackoverflow";
I want to print that string one character at a time with some delay after each character:
int i = 0;
while (str[i] != '\0') {
putchar(str[i]);
usleep(100000);
i++;
}
But instead of doing the obvious and right thing, printing a character and waiting 100 ms and doing it over again, it looks like the delay gets accumulated and spit out at once.
So it sleeps happily for about one and a half second and then prints out my string.
Any ideas?
(I did the exact same thing in Ruby without a problem and also tried it using the ‘\r’-method, which also works in Ruby …)
Please help!
Otherwise I can’t do the program for my assignment, which is printing a string; but I don’t want to do it boringly … 😉
Thank you!
Try to flush the buffer in between:
When writing to a terminal, output is usually line-buffered. The actual thing is printed if a
\nis encountered or if the buffer fills.Alternatively you could disable buffering once and for all at the beginning: