Jic*_*hao 12 c++ string random
我正在寻找在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;
}
Run Code Online (Sandbox Code Playgroud)
但这seed(time(NULL))不是随机的.还有其他更好的方法在C++中生成随机字符串吗?
sha*_*oth 25
不要调用srand()每个函数调用 - 只在第一次函数调用或程序启动时调用它一次.你想要一个标志,表明是否srand()已经被调用.
除了你滥用srand()并获得可预测的不良结果之外,这种方法很好.