Select Page

Randomness is all around us. We see it when distributing cards, or when tossing a coin. Even in the legal world, trial juries are still formed today via randomized selection in the United States and in other common law systems.

As a C++ programmer, you’ll no doubt have to generate and include random numbers in your programs. Whether you’re creating a game or an advanced security algorithm, you’ll need to be proficient in the topic. 

So, what does “random” mean in C++ and how do we create random numbers? We address these questions below. 

What Does Randomness Really Mean in C++?

True randomness does not exist in software. All calculations done by a computer’s CPU need to start with an input, and if that input isn’t random, the result can’t be random either. Modern processors can produce results that look random to us, however, thanks to advanced randomness simulation techniques and algorithms.

What we commonly call “random number generators” are in fact pseudorandom number generators, which simulate randomness rather than “creating” it. For most uses that don’t involve encryption or information security, pseudorandom numbers are sufficient. High-security programs, such as banking portals, require true random number generators that use a physical phenomenon to extract randomness, such as the atmospheric noise.

There are a few situations in today’s programming world where pseudorandomness has become extremely useful:

  • The One Time Password (OTP) authentication protocol is used to generate a single-use code for the purpose of logging in to a website or an application. The generated one-time token is partly based on a secret the user has, but also includes a random part.
  • Machine learning (ML) uses randomness to improve accuracy and performance. Due to the specifics of how ML algorithms work, the order in which an algorithm observes data has an impact on the resulting ML model. By randomizing inputs during the training process, ML engineers can work around any potential issues related to the order of observation.
  • In statistics, we use random samples to ensure that a dataset accurately represents the variety that exists in the initial data.

Using C++’s built-in pseudorandomness capabilities can take you a long way in creating robust and valuable C++ programs. 

How To Make a Random Number Generator in C++

The C++ 11 standard, approved in 2011, introduced many new features in the language, one of these being the random library. Its goal was to replace the standard function rand() and provide better randomness simulation. While some C++ tutorials still advise using rand(), this article will focus on the most up-to-date way of creating a random number generator in C++ by using the powerful random library.

The random library includes tools enabling you to get non-deterministic data based on your computer hardware. For example, the function random_device from this library implements pseudo-random generator algorithms such as Mersenne Twister.

Note: if you’re using GCC as your compiler, you might need to pass the flag -std=c++11 when compiling the code examples from this article.

Who Gets To Go to the Cinema?

Let’s say a group of friends just got their hands on the last available ticket for the latest Tarantino movie. But there are 8 people in the group. To decide who gets the ticket, the friends create a random number generator in C++. Here’s how it might look: 

int main()
{
	// STEP 1
	random_device rd;

	// STEP 2
	mt19937 generator(rd()); 
   
	//STEP 3
	uniform_int_distribution<> range(1, 8);

	// STEP 4
	cout << "And the winner is... number " << range(generator) << "!!!";
}

Here’s what the above code does:

STEP 1: We declare a random_device object that we’ll use to generate a random number.

STEP 2: The Mersene Twister engine is an algorithm included in the random library that generates a very large pseudorandom result based on the initial number that’s given in input. We define a generator object and instruct it to use the random_device we created previously as the source of randomness (or “seed”).

STEP 3: Here, we create a uniform distribution object. It’s designed to turn the pseudorandom result from Step 2 into a random digit between 1 and 8.

STEP 4: On this step we generate a random number between 1 and 8 using the generator object from Step 2 and the uniform distribution object from Step 3. We then print the result to standard output.

Our program’s output is as follows:

And the winner is... number 5!!!

With the help of the random library, you can generate quality pseudorandom numbers in C++ with just a few lines of code. But what if you wanted to do something a bit more specific?

Make A Password Generator

People tend to choose passwords that are easy to recall, but quite simple to guess for a computer using brute force or dictionary-based attacks. You could improve your program’s security by offering users generated passwords, which are complex enough for a machine to guess. Here’s how the code could look like for the random password generator:

...
int main()
{
// Let's declare two variables, one for the loop and
// the other for the password length
int i, passwordLength;
   
// Now, we ask the user to provide a password length,
// and we check the validity of his answer
cout << "Welcome to a Great Password Generator!";
cout << "Please input the desired password length (minimum 8 characters" << endl;
cout << ">";
cin >> passwordLength;
   
// Check if the player entered the data correctly
while (!cin || passwordLength < 8 ) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Error: Please enter a number, the minimum is 8!" <<        endl;
        cout << "> ";
        cin >> passwordLength;
}
...

In the first part of the program, we make sure to get the required user input, which can only be an integer that’s eight or more (to indicate a desired length of our random password). The input will be our basis for generating a random password.

...
// We declare an array for the password.
// Its size is the user's input
char password[passwordLength];
   
// We use a for loop to generate as many integers as needed
// Within a selected range of ASCII characters
for (int i = 0; i < passwordLength; i++){
        // We use the random-device generator
        random_device rd;

        // Then we call the Mersenne twister engine again
        mt19937 gen(rd());
 
        //We distribute the results between 33 and 126 inclusive
        // to include common English keyboards characters
        uniform_int_distribution<> dist(33, 126);

        //We assign a value to each element of the array
        password[i] = dist(gen);
}
   
// We display a message and the content of the array;
cout << "Your brand new password is: " << password;
}

The next section of the code creates an array of characters that will store the randomly generated password, and whose size is the value of passwordLength. We then generate random numbers within the ASCII printable characters range (minus space and delete characters) for each element of the array.

When we compile and run the program, the output is as follows::

Welcome, Welcome to a Great Password Generator!
Please input the desired password length (minimum 8 characters)
>12
Your brand new password is: 7H*uIP~Xk'6G

There are 93 possibilities in the ASCII printable characters range we selected. The number of possible 12-character passwords is 93 to the power of 12, which equals ~4.19*10^23. It would take many years for a computer to guess a password like that.

Learn C++ Online With Udacity

There are plenty of uses for a random number generator. These can be as simple as allocating a cinema ticket to one of eight individuals, or as complex as creating a security encryption system. The random library allows you to easily generate random numbers in C++ and add randomness to your applications.

Want to become a C++ developer? 

Get started by enrolling in our C++ Nanodegree program!

Complete Code Examples

Program 1:

#include <random>
#include <iostream>

using namespace std;

int main()
{
	// STEP 1
	random_device rd;

	// STEP 2
	mt19937 generator(rd()); 
   
	//STEP 3
	uniform_int_distribution<> range(1, 8);

	// STEP 4
	cout << "And the winner is... number " << range(generator) << "!!!";
}

Program 2:

#include <iostream>
#include <random>
using namespace std;


int main()
{
// Let's declare two variables, one for the loop and
// the other for the password length
int i, passwordLength;
   
// Now, we ask the user to provide a password length,
// and we check the validity of his answer
cout << "Welcome, I am Great Password Generator, your best ";
cout << "virtual Friend and I work for your safety !" << endl;
cout << "First, tell me how long your password should be ?" << endl;
cout << "(Please input a number higher than 8)" << endl;
cout << ">";
cin >> passwordLength;
   
// Check if the player entered the data correctly
while (!cin || passwordLength < 8 ) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Error: Please enter a number, not shorter than 8 !" <<        endl;
        cout << "> ";
        cin >> passwordLength;
}
// We declare an array for the password.
// Its size is the user's input
char password[passwordLength];
   
// We use a for loop to generate as many integers as needed
// Within a selected range of ASCII characters
for (int i = 0; i < passwordLength; i++){
        // We use the random-device generator
        random_device rd;

        // Then we call the Mersenne twister engine again
        mt19937 gen(rd());
 
        //We distribute the results between 33 and 126 inclusive
        // to include common English keyboards characters
        uniform_int_distribution<> dist(33, 126);

        //We assign a value to each element of the array
        password[i] = dist(gen);
}
   
// We display a message and the content of the array;
cout << "Your brand new password is: " << password;
}