问题
I'm trying to program a simple "typewriter" effect in C, where text appears one letter at a time with a delay. Here's the function I have:
#include <stdio.h>
#include <unistd.h>
void typestring(const char *str, useconds_t delay)
{
while (*str) {
putchar(*(str++));
usleep(delay);
}
}
The problem is the text doesn't actually appear until a \n
is displayed. What am I doing wrong?
回答1:
The output to stdout
is buffered. Using \n
you are forcing a flush. If you want to change this, you will need to change the settings of the terminal (for Linux look here) or use
void typestring(const char *str, useconds_t delay)
{
while (*str) {
putchar(*(str++));
fflush(stdout);
usleep(delay);
}
}
回答2:
Your output stream might have get buffered, '\n'
flushes the buffer.
Try fflush(stdout
after putchar()
, as
while (*str) {
putchar(*(str++));
fflush(stdout);
usleep(delay);
}
回答3:
\n
implicitly forces output device to flush buffered input. To flush you should explicitly use fflush:
fflush(stdout);
回答4:
Output Stream is buffered that's why text doesn't actually appear until a \n is displayed '\n' flushes the output stream (hard flush) to do manually the same you can call this function [fflush(stdout)].
while (*str) {
putchar(*(str++));
fflush(stdout);
usleep(delay);
}
or you can use
while (*str) {
printf("%c\n",*(str++));
usleep(delay);
}
来源:https://stackoverflow.com/questions/16142384/output-not-displayed-with-usleep-until-a-line-break-is-given