How to generate random string in C++

Generating random strings will be helpful in many applications. As strings are arrays of characters and characters are stored as numbers the problem comes down to generating random characters. However, this can be quickly done with principles of random number generation.

C++ program for generating a random string of a given length

The rand() function seeded with current time is used for generating random numbers. Just like two values being generated for random Boolean values in this article, The random numbers can be generated between 0 and 25 each of which can represent alphabets from (a to z).

These values are generated as many times as required(length of the string) and are inserted into a string value(The result).

The following code illustrated the point:

#include <iostream>
#include <string>
std::string generate(int n)// n is size of the random string
  std::string result{};
  for (int i = 0; i < n; i++)
    int g = std::rand()%25;
    char d = static_cast<char> (g + 'a'); // generating random char
  return result;

int main()
  std::srand(time(0)); //seeding random generator 
  int n=1;
  while (n!=0)
    std::cout << "enter the size of a random string and 0 to exit:"; std::cin >> n;
    if (n > 0)
      std::string res = generate(n);
      std::cout << "a random string of size " << n << " is:\n"<<res<<std::endl; // printing random string

enter the size of a random string and 0 to exit:5
a random string of size 5 is:
enter the size of a random string and 0 to exit:10
a random string of size 10 is:
enter the size of a random string and 0 to exit:15
a random string of size 15 is:
enter the size of a random string and 0 to exit:0

If required capital letters and other 128 ASCII symbols can be incorporated into generating a random string. The basic principle remains the same just to extend the range from 25 to 128.

But for the sake of demonstration and simplicity, only small Latin letters are used for generating random strings in this article.

Leave a Reply

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