-4

I would like to print a text slowly letter by letter like in this example

//example
int main()
{
    string message = "Lorem ipsum dolor sit amet, \nconsectetur adipisicing elit. Voluptatum, porro \nnesciunt laboriosam adipisci provident eum?\n";
    slow_print(message, 30);

    return 0;
}

but i want to have this effec twith the cout command but i dont find any solutions. If someone know how to fix this so please helpe me

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Georges
  • 1
  • 1

3 Answers3

3

Ok, lets do this using cout. cout alone cannot do it, you need some io-manipulator or similar. I will use a type to indicate a string should be printed slowly:

struct slowly_printing_string { 
    std::string data; 
    long int delay; 
};

Next, we provide an output operator for this type:

std::ostream& operator<<(std::ostream& out, const slowly_printing_string& s) {
    for (const auto& c : s.data) {
        out << c << std::flush;        
        std::this_thread::sleep_for(std::chrono::milliseconds(s.delay));
    }
    return out;
}

It prints individual characters, flushes the stream (otherwise it could happen that you only see the full string at some later point), and waits for the specified time.

You can call it like this:

std::cout << slowly_printing_string{"hello world",1000};

Full Example

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

I can do this by this code, but I don't recommend this code if you are developping to an enterprise:

#include <iostream>

#define LENGTH(x) (sizeof(x) / sizeof(x[0]))

using namespace std;

void printSlowCharacters(char * strToPrint) {
    while(*strToPrint) {
        cout << *strToPrint++ << endl;
        system("sleep 5");
    }
}


int main() {
    char * nome = "Davi";
    printSlowCharacters(nome);

    return 0;    
}
0

You can use #include <windows.h> and then in a loop you would print each character individually and intertwine it with Sleep(time_in_ms).

How is it possible? Each std::string is an array of characters, which is similar to char*, that way you can access each character by its index.

whiskeyo
  • 873
  • 1
  • 9
  • 19