I want to generate multiple random alphanumeric string within one second, but my code always gives the same string, I understand that it is because the time () (typically) has a resolution of 1 second. Is there any way to solve this?
Here is my code:
#include <iostream>
#include <ctime>
#include <unistd.h>
using namespace std;
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
int main(int argc, char *argv[]) {
cout << gen_random(4) << " and " << gen_random(5) << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire