Search code examples
c++text

How to make a "gradual" text function in C++?


So, I wanted to make a text adventure in C++, and I wanted to create a cool function that allowed the text to be displayed letter-by-letter gradually, like in movies.

The issue is that my code isn't displaying it one letter at a time, but waiting and then displaying it all at once, defeating the whole purpose.

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

void cool_text(std::string text) {
    for (char letter: text) {
        std::cout << letter;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

    }
}

int main() {
    cool_text("Programing");
}

However, if I were to write line 7 like so...

std::cout << letter << std::endl;

...then it displays it letter-by-letter, but even that isn't consistent.

How should I go about this? Any help appreciated. (If it helps, I'm using an online editor on a Chromebook.)


Solution

  • The output is buffered and usually won't be displayed until you output a newline. You can however force it out using std::flush:

    std::cout << letter << std::flush;
    

    std::cout << letter << std::endl; ...then it displays it letter-by-letter, but even that isn't consistent.

    std::endl is a combination of \n + std::flush and if that's not consistent you could replace sleep_for with sleep_until with a time point that you add 100ms to in every iteration:

    void cool_text(const std::string& text) {
        auto tp = std::chrono::steady_clock::now();
        for(char letter : text) {
            std::cout << letter << std::flush;
            tp += std::chrono::milliseconds(100);
            std::this_thread::sleep_until(tp);
        }
    }
    

    This should make it a bit more consistent.