0

I am newbie in C and have some doubts in my code.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void TypeText(char text[]){
   for (int i=0; i<=strlen(text); i++)
   {
      printf("%c", text[i]);
      sleep(1);
   }
}

int main(){
  TypeText("This is the year 2086...");

  return 0;
}

I'm trying to create a typing effect and I thought this code should work very well. It should print one string of the text per second, however its shows the whole text after 24s (24 is the size of my text). I realized that if put a "\n" in the printf it works how it should, although I wouldn't want to skip a line in every string

printf("%c\n", text[i]);

I am using the last version of Ubuntu

Thank anyone who can help me

  • 1
    User-output is *line-buffered* by default. (meaning output isn't shown until a `'\n'` is entered). You can change the line buffering to do what you are attempting to do. You can simply add `fflush(stdout);` after each call to `printf()` (which you should be using `putchar(text[i]);` to output a single character -- no need to call `printf()` when there are no conversions involved...) – David C. Rankin Oct 24 '20 at 06:03
  • No need for `strlen()`, you can simply loop `for (int i=0; text[i]; i++)`. Every string in C ends with a *nul-terminating* character (which has ASCII value `0`), so you can just scan forward in the string until you *nul-terminating* character is reached which causes your loop test clause to test `false` and the loop exits... – David C. Rankin Oct 24 '20 at 06:08
  • Instead of `printf("%c", text[i])` you can just use plain `putchar` – Antti Haapala Oct 24 '20 at 07:23

0 Answers0