In: Computer Science
Need a c++ program to generate a random string of letters between 8 and 16 characters.
C++ code for the given problem statement:
#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
// Returns a string of random alphabets of
// length between 8 to 16 characters
string printRandomString()
{ int num = (rand() % (16 - 8 + 1)) + 8;
char alphabet[MAX] = { '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 res = "";
for (int i = 0; i < num; i++)
res = res + alphabet[rand() % MAX];
return res;
}
// Driver code
int main()
{
srand(time(NULL));
cout << printRandomString();
return 0;
}
Editor Screenshot:
Sample Output:
I hope you find the solution helpful.
Keep Learning!