Generate a random password of a specific length in C++

Hello everyone in this tutorial we are going to learn how to generate a random password of a specific length in C++. We are going to start the code.

What is random function?

Random function is used here to generate a random sequence of strings or numbers etc . The random function comes under the library cstdlib in codeblocks in C++. Similarly, we can also use random function in different C++ platforms with their specific libraries.
The random function can be created alphanumeric. Now alphanumeric consists of letter and number in C++. We use random alphanumeric string to create a alphanumeric value of different sizes.
Random function is giving us the random value generated by the system. The system is generating different values at each run. The random values differ from machine to machine i.e. we can create as many values we want.

Creating a random password of specific length in C++

The password contains sets like alphabets, number and special symbols. The random function is used to create a password.

const char alphanum[] = "[email protected]#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

This constant contains the number, special symbol and alphabets(in both cases) used for generating random passwords. We can user-defined value for the length to generate the random passwords.

#include <iostream>
using namespace std;
const char alphanum[] = "[email protected]#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int string_length = sizeof(alphanum)-1;
int main()
    int n;
    cout<<"Enter the length of password:";
    cout<<"Generated password:";
    for(int i = 0; i < n; i++)
    cout << alphanum[rand() % string_length];
    return 0;

We have created a constant with our values of random password. Then using random function we are calling that constant randomly to create random passwords. We have used cstdlib library for random function. A few sample programs with different user-defined values.

The first output:

Enter the length of password:8
Generated password:i^FjD&9%

The second output:

Enter the length of password:7
Generated password:xne8rWm

The third output:

Enter the length of password:12
Generated password:nDzq!qf$tqV$

The fourth output:

Enter the length of password:4
Generated password:*[email protected]

In the previous sample output, we have created a random password on specific lengths provided by the user at the run time.  We can create as many as password because of our code.  Now your new password is ready which suggests a secure and if not try another one. The random password generator use in various platforms and in fact.

Leave a Reply

Your email address will not be published. Required fields are marked *