简体   繁体   中英

getting text to print character by character in C

int main() {
    int i;
    char words[] = "Hello this is text.\n";
    for(i = 0; i < strlen(words); i++) {
        sleep(1);
        putchar(words[i]);
    }
}

I've been attempting to have the program output the text slowly, character by character into the console (to look like someone is typing it). However instead when I run this code I get one massive pause, and then it prints the whole string at once. How do I get this to work.

(also no C++ solutions please)

stdio is buffered to make it more efficient, writing a single character isn't enough to get it to write it's buffer to the console. You need to flush stdout:

#include <stdio.h>

int main() {
    int i;
    char words[] = "Hello this is text.\n";
    for(i = 0; i < strlen(words); i++) {
        sleep(1);
        putchar(words[i]);
        fflush(stdout);
    }
}

That's because the standard output is line buffered by default.

Flush the output after each character like this:

putchar(words[i]);
fflush(stdout);  //<---

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM