2

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);
  }
}
  • 6
    Not `sizeof(d1)` but `d1.size()` – Louis Go May 15 '22 at 08:44
  • 2
    `sizeof(d1)` gives the size of the object `d1`, not the length of the string it contains. Use `d1.size()` instead – phuclv May 15 '22 at 08:44
  • 1
    Decent first effort, but I calculate that your program (it's a program, not a script) is going to take 24 seconds to run, and that's too long. Do you know about [`usleep`](https://man7.org/linux/man-pages/man3/usleep.3.html)? But, better still (although a little harder to master), use [`std::chrono_sleep_for`](https://en.cppreference.com/w/cpp/thread/sleep_for). – Paul Sanders May 15 '22 at 08:49
  • 2
    You should include the C++ headers, not the C ones. `#include `. But I don't think you even need it here. – infinitezero May 15 '22 at 08:52
  • You are looping through string so it will basically just print that string again for you – Mushfiqur Rahman Abir May 15 '22 at 08:53
  • @MushfiqurRahmanAbir But with a `sleep` between each character, that's the whole point... – Paul Sanders May 15 '22 at 08:54
  • I think that's called "ghost typing" – MatG May 15 '22 at 11:06

2 Answers2

3

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().

Chris
  • 26,361
  • 5
  • 21
  • 42
TonyK
  • 16,761
  • 4
  • 37
  • 72
0

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));
    }
}
GameWin221
  • 44
  • 1
  • 3