enlightened
enlightened

Reputation: 59

Print a string char by char with a delay after each char

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!

Upvotes: 0

Views: 7674

Answers (3)

Moo-Juice
Moo-Juice

Reputation: 38810

You need to call fflush(). The characters are getting buffered up.

Upvotes: 0

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

It's not the delay that gets accumulated and spit out at once, it's the string (note that when you execute your program, the delay comes before the string is printed, not after it).

Flush the standard output after each char:

fflush(stdout);

Upvotes: 0

cnicutar
cnicutar

Reputation: 182664

Try to flush the buffer in between:

putchar(str[i]);
fflush(stdout);
usleep(100000);

When writing to a terminal, output is usually line-buffered. The actual thing is printed if a \n is encountered or if the buffer fills.

Alternatively you could disable buffering once and for all at the beginning:

setbuf(stdout, NULL);

Upvotes: 5

Related Questions