如何使用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
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短