Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate random strings in C++?

Tags:

c++

string

random

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;
}

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

like image 440
Jichao Avatar asked Jan 27 '10 12:01

Jichao


1 Answers

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.

like image 191
sharptooth Avatar answered Oct 04 '22 17:10

sharptooth