生成隨機字母的 C++ 程式
在本教程中,我們將討論一個生成隨機字母的程式。
為此,我們需要一個固定大小的陣列/字串,並使用 rand() 函式生成一個隨機字母字串。
示例
#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
//generating a string of random alphabets
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP