我正在寻找在 C++ 中生成随机字符串的方法。这是我的代码:
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
srand(time(NULL));
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
但是 seed(time(NULL))
不够随机。有没有其他更好的方法在 C++ 中生成随机字符串?
最佳答案
不要在每个函数调用上调用 srand()
- 只在第一次函数调用或程序启动时调用它一次。您可能希望有一个标志来指示 srand()
是否已被调用。
建议的方法很好,只是您误用了 srand()
并得到可预见的坏结果。
关于c++ - 如何在 C++ 中生成随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146792/