In this section we will see how to generate a random alphanumeric string using C++. Here we are providing lowercase letters, uppercase letters and numbers (0-9). This program takes the characters randomly, then creates the random string.
Input: Here we are giving the string length Output: A random string of that length. Example “XSme6VAsvJ”
Algorithm
Step 1:Define array to hold all uppercase, lowercase letters and numbers Step 2: Take length n from user Step 3: Randomly choose characters’ n times and create a string of length n Step 4: End
Example Code
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(alphanum) - 1;
char genRandom() { // Random string generator function.
return alphanum[rand() % len];
}
int main() {
srand(time(0));
int n;
cout << "Enter string length: ";
cin >> n;
for(int z = 0; z < n; z++) { //generate string of length n
cout << genRandom(); //get random character from the given list
}
return 0;
}Output
Enter string length: 10 XSme6VAsvJ