Search code examples
cterminaloutputputchar

Output not displayed with usleep until a line break is given


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?


Solution

  • 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);
        }
    }