如何在C ++中生成随机字符串? [英] How do you generate random strings in C++?

查看:799
本文介绍了如何在C ++中生成随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在C ++中生成随机字符串的方法。这是我的代码:

I am looking for methods to generate random strings in C++.Here is my code:

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 ++中有没有其他更好的方法来生成随机字符串?

But the seed(time(NULL)) is not random enough.Are there any other better way to generate random strings in C++?

推荐答案

Don在每个函数调用上调用 srand() - 在第一次函数调用或程序启动时只调用一次。您希望有一个标志指示 srand()是否已被调用。

Don't call srand() on each function call - only call it once at first function call or program startup. You migh want to have a flag indicating whethersrand() has already been called.

除非您误用 srand(),并得到可预测的错误结果。

The sugested method is good except that you misuse srand() and get predictably bad results.

这篇关于如何在C ++中生成随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆