How to create a random string in C++?
Here we see how to create a random string in C++ using predefined functions.
The solution basically comprises of usage of rand() and srand() functions under <bits/stdc++.h>header.
The rand() function randomly generates integer values .This function is always accompanied by srand() function. The srand() function sets the starting point for producing these random integers. Generally, as a practice, we take input as srand(time (NULL)) or srand(time(0)) initializing it a system time whose value will increase the randomness of integers generated.
To create random strings in C++
Firstly, we create an array of alphabets and initialize a string variable ran and initialize it to ” “. To this we add letters combination for required result. We define MAX_SIZE as the number of alphabets-26 in our case. This could be generalized for other cases. Then, we run a loop of wanted word length and for each loop, we do the following :
ran=ran+letters(rand()%MAX_SIZE)
In the main() function, we firstly take input for integer variable num i.e. the word length of the random words we wish to generate.
Sample Code:
#include <bits/stdc++.h> using namespace std; const int MAX_SIZE = 26; string printstring(int n) { char letters[MAX_SIZE] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q', 'r','s','t','u','v','w','x', 'y','z'}; string ran = ""; for (inti=0;i<n;i++) ran=ran + letters[rand() % MAX_SIZE]; return ran; } int main() { srand(time(NULL)); cout<<"enter the value of num:\n"; cin>>num; cout << printstring(num); return 0; }
Enter the value of num:8
sbizaskv
Also Read:
Leave a Reply