Output console text with type-writer effect. source code

This snippet submitted by Michael Brandon Miller on 2013-02-01. It has been viewed 89985 times.
Rating of 7.4 with 491 votes

 // Author : Michael Brandon Miller
// Email  : lectisoft@gmail.com
//
// This snippet requires the Boost C++ Library.

#include <string>
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

using namespace std;
using namespace boost;

// The pseudo-random number generator.
random::mt19937 NumGenerator;

// Perform typing effect on std::string.
void type_text(string text)
{
	String::const_iterator end = text.end();
	random::uniform_int_distribution<> range(-75, 50);

	for (String::const_iterator it = text.begin(); it != end; ++it) {
		cout << *it;

		// Sleep for anywhere from 25ms to 150ms.
        this_thread::sleep(posix_time::milliseconds(100 + range(NumGenerator)));
    }
}

// Perform typing effect on C-String.
void type_text(const char *text)
{
	unsigned int length = strlen(text);
	random::uniform_int_distribution<> range(-75, 50);

	for (unsigned int i = 0; i < length; i++) {
		cout << text[i];

		// Sleep for anywhere from 25ms to 150ms.
		Sleep(100 + range(NumGenerator));
	}
}

int main(int argc, char **argv)
{
    string text_to_type = \"Hello World! Testing, testing, 1 2 3...\";
    type_text(text_to_type);
    
    return 0;
}
 
 




More C and C++ source code snippets

Add a snippet!