开发者

How do you generate random strings in 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() % charse开发者_如何转开发t.length()];

    return result;
}

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


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.

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


You can use Boost.Random. It uses a different generator than the one provided with most standard libraries, that should be more robust.

In specific, most standard libraries provide linear congruential generators, which don't perform very well when you mod their results with small numbers. Boost.Random has a Mersenne twister generator.

As sharptooth says, though (good spotting!), only seed the generator once, at the very start of your program. Seeding it every time you want something random is counter-productive.


Make an interface to get a random number in this site http://www.random.org/ and you will be sure to get a real random number! But if you are looking for performance...


On unix systems you can read random values from the file /dev/random


If you prefer to use the standard library, then you can do something like this:

<somewhere else>
srand(NULL);
</somewhere else>

char get_rand_char() {
  static string charset(...);
  return charset[rand() % charset.size()];
}

std::string generate_random_string(size_t n) {
  char rbuf[n];
  std::generate(rbuf, rbuf+n, &get_rand_char);
  return std::string(rbuf, n);
}

This code is naturally more modular, and standard library maintainers tend to write better code than me. This way I can change the random character generating part of the code without touching anything else. I could even forward to a function that randomly picks a random number generator! Not that it would compound the randomness or anything...


use std::generate_n. This way you can specify the length of your generated string. In the below case its 4.

std::string uniqueName() {
    auto randchar = []() -> char
    {
        const char charset[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        const size_t max_index = (sizeof(charset) - 1);
        return charset[ rand() % max_index ];
    };
    std::string str(4,0);
    std::generate_n( str.begin(), 4, randchar );
    return str;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜