Reputation: 211
I use this the generate random string in Qt:
GenerateRandomString()
{
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
const int randomStringLength = 5; // assuming you want random strings of 5 characters
QString randomString;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
return randomString;
}
however the strings it generates repeat every time I start the debug (or run the program). It seems like qrand() is seeded the same every time. How can I properly reseed qrand() so that it is more random? Thank you.
Upvotes: 0
Views: 2245
Reputation: 9668
As an alternative to @Yep's answer, since QDateTime::toTime_t()
is deprecated since Qt5.8
, the following will work just as well:
qsrand(QDateTime::currentMSecsSinceEpoch()%UINT_MAX);
Upvotes: 1
Reputation: 211
I found a solution... I add this to the constructor so the program is seeded differently every time. It works for my purpose.
QDateTime cd = QDateTime::currentDateTime();
qsrand(cd.toTime_t());
Upvotes: 3