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++?
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++?
void gen_random(char *s, const int len) {
for (int i = 0; i < len; ++i) {
int randomChar = rand()%(26+26+10);
if (randomChar < 26)
s[i] = 'a' + randomChar;
else if (randomChar < 26+26)
s[i] = 'A' + randomChar - 26;
else
s[i] = '0' + randomChar - 26 - 26;
}
s[len] = 0;
}
Could you generate GUID's from the built in function(s) and then just trim off the length you need?
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[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
I tend to always use the structured C++ ways for this kind of initialization. Notice that fundamentally, it's no different than Altan's solution. To a C++ programmer, it just expresses the intent a tad better and might be easier portable to other data types. In this instance, the C++ function generate_n
expresses exactly what you want:
struct rnd_gen {
rnd_gen(char const* range = "abcdefghijklmnopqrstuvwxyz0123456789")
: range(range), len(std::strlen(range)) { }
char operator ()() const {
return range[static_cast<std::size_t>(std::rand() * (1.0 / (RAND_MAX + 1.0 )) * len)];
}
private:
char const* range;
std::size_t len;
};
std::generate_n(s, len, rnd_gen());
s[len] = '\0';
By the way, read Julienne’s essay on why this calculation of the index is preferred over simpler methods (like taking the modulus).
I just tested this, it works sweet and doesn't require a lookup table. rand_alnum() sort of forces out alphanumerics but because it selects 62 out of a possible 256 chars it isn't a big deal.
#include <cstdlib> // for rand()
#include <cctype> // for isalnum()
#include <algorithm> // for back_inserter
#include <string>
char
rand_alnum()
{
char c;
while (!std::isalnum(c = static_cast<char>(std::rand())))
;
return c;
}
std::string
rand_alnum_str (std::string::size_type sz)
{
std::string s;
s.reserve (sz);
generate_n (std::back_inserter(s), sz, rand_alnum);
return s;
}