如何使用 C++ 创建一个随机字母数字字符串?


本节中,我们将了解如何使用 C++ 生成一个随机字母数字字符串。此处我们提供小写字母、大写字母和数字 (0-9)。此程序随机选取字符,然后创建随机字符串。

Input: Here we are giving the string length
Output: A random string of that length. Example “XSme6VAsvJ”

算法

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

示例代码

 在线演示

#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;
}

输出

Enter string length: 10
XSme6VAsvJ

更新于: 2019 年 7 月 30 日

766 次观看

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.