如何在 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
生成质量较差的随机数.
相关文章