Output not displayed with usleep until a line break is given

耗尽温柔 提交于 2019-12-12 01:08:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!