Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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

\n implicitly forces output device to flush buffered input. To flush you should explicitly use fflush:

 fflush(stdout);

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);
        }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top