Home > database >  C Typewriting Effect
C Typewriting Effect

Time:05-16

So I'm trying to make typewriting effect print in C and the error is the script give me the final result instead of the typewriting effect.

#include <iostream>
#include <stdlib.h>
#include <unistd.h>

int main() {
  std::string d1 = "\"Starting in 3, 2, 1...\"";
  for(int i = 0; i < sizeof(d1); i  ){
    std::cout << d1[i];
    sleep(1);
  }
}

CodePudding user response:

What with those other problems, everybody seems to have missed the point here, which is that std::cout is buffered (on most systems). So it is waiting for the newline before displaying the text. Try calling std::cout.flush() before every call to sleep().

CodePudding user response:

First of all don't use sizeof(d1) which returns the size in bytes of the string but use d1.size() which return the length of the string. Also, I have no idea where did you get that sleep() function from. Use std::this_thread::sleep_for(std::chrono::milliseconds({time_in_milliseconds})); instead (you will need to #include <thread>).

Working example:

#include <iostream>
#include <string>
#include <thread>

int main() {
    std::string d1 = "\"Starting in 3, 2, 1...\"";

    for (int i = 0; i < d1.size(); i  ) 
    {
        std::cout << d1[i];
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}
  •  Tags:  
  • c
  • Related