Ask coding questions

← Back to all posts
SlowPrint [C++]
Bookie0 (5937)

Hi how to add slowPrint to C++?

like this is it in python:

import os, time
st = 0.04
def sp(str):
  for letter in str:
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(st)
  print()

sp("hi")

but how to do in C++?

(im making a game and we have to finish it quick for a camp so thats why im asking for help i also tried googling it ;)

thanks!

Answered by Coder100 (16757) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16757)

Ok! Done! repl

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

using namespace std;

void slow_print(const string& message, unsigned int millis_per_char=10) {
  for (const char c : message) {
    // flush is used to make sure the console is empty
    cout << c << flush;

    // Ask the thread to sleep for at least n millis.
    this_thread::sleep_for(chrono::milliseconds(millis_per_char));
  }
}

int main() {
  slow_print("I am slow also C++ is the best Coder100 out.", 50);
}
Bookie0 (5937)

@Coder100 thank you. thank you. thank you.

Coder100 (16757)

no problem! no problem! no problem! @Bookie0