C ++程序生成随机字母

在本教程中,我们将讨论生成随机字母的程序。

为此,我们将使用固定大小的数组/字符串,并使用该rand()函数生成随机的字母字符串。

示例

#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
//生成一串随机字母
string gen_random(int n){
   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 < n; i++)
      res = res + alphabet[rand() % MAX];
   return res;
}
int main(){
   srand(time(NULL));
   int n = 7;
   cout << gen_random(n) << endl;
   return 0;
}

输出结果

gwqrgpa