jm. jm. - 6 days ago 4x
C++ Question

How do I create a random alpha-numeric string in C++?

I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.

How do I do this in C++?


Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

void gen_random(char *s, const int len) {
    static const char alphanum[] =

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];

    s[len] = 0;