本文介紹了如何在 C++ 中創建一個隨機的字母數字字符串?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想創建一個隨機字符串,由字母數字字符組成.我希望能夠指定字符串的長度.
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.
我如何在 C++ 中做到這一點?
How do I do this in C++?
推薦答案
Mehrdad Afshari 的 answer 可以解決問題,但我發現它對于這個簡單的任務來說有點過于冗長.查找表有時可以創造奇跡:
Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:
#include <ctime>
#include <iostream>
#include <unistd.h>
std::string gen_random(const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string tmp_s;
tmp_s.reserve(len);
for (int i = 0; i < len; ++i) {
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
}
return tmp_s;
}
int main(int argc, char *argv[]) {
srand((unsigned)time(NULL) * getpid());
std::cout << gen_random(12) << "
";
return 0;
}
請注意,rand
生成質量較差的隨機數.
這篇關于如何在 C++ 中創建一個隨機的字母數字字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!