2
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)

Mr.Prime
  • 21
  • 3
  • can u use function usleep, here you can pass arguments in miliseconds instead of seconds. Also look at http://stackoverflow.com/questions/14818084/what-is-the-proper-include-for-the-function-sleep-in-c – lordkain Jul 27 '16 at 06:22
  • 3
    use [`fflush`](http://linux.die.net/man/3/fflush) after putchar – dvhh Jul 27 '16 at 06:22

2 Answers2

4

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);
    }
}
kfsone
  • 23,617
  • 2
  • 42
  • 74
3

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

Flush the output after each character like this:

putchar(words[i]);
fflush(stdout);  //<---
Yu Hao
  • 119,891
  • 44
  • 235
  • 294