std::rand() create same string
-
Hello Friends and Qt Experts.
Right now i am working on Randomization
i want to Generate unique string from my software every time.Here is my code.
QString MainWindow::GenerateRandomString(int StringLength) { const QString PossibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); QString RandomGeneratedString; for(int i = 0; i < StringLength; i++) { int index = std::rand() % PossibleCharacters.length(); QChar NextCharacter = PossibleCharacters.at(index); RandomGeneratedString.append(NextCharacter); } return RandomGeneratedString; }
this function working well n good
but when i restart the my application
i am getting same string which is previously generated.(Before restart the Application.)Result is ::
/////// First Time Generated Strings ///////
F98ER24S8U
R3ZPZXH0DA
1YOJE8760X
LSLS7E9TH4
LPCV7UVH32/////// Second Time Generated Strings (After Restart The Application) ///////
F98ER24S8U
R3ZPZXH0DA
1YOJE8760X
LSLS7E9TH4
LPCV7UVH32Please help me to solve my problem.
Thanks in advance. -
With
std::rand()
you need to seed your generator with a different value. Traditionally a common choice is current time. A more modern one is std::random_device. See std::srand() for details.As a side note - rand() and % is not a very good way to generate random numbers in a range. It can result in a biased distribution. If you want a number from a given range use a proper dedicated distribution function: std::uniform_int_distribution.
-
Hello Friends and Qt Experts.
Right now i am working on Randomization
i want to Generate unique string from my software every time.Here is my code.
QString MainWindow::GenerateRandomString(int StringLength) { const QString PossibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); QString RandomGeneratedString; for(int i = 0; i < StringLength; i++) { int index = std::rand() % PossibleCharacters.length(); QChar NextCharacter = PossibleCharacters.at(index); RandomGeneratedString.append(NextCharacter); } return RandomGeneratedString; }
this function working well n good
but when i restart the my application
i am getting same string which is previously generated.(Before restart the Application.)Result is ::
/////// First Time Generated Strings ///////
F98ER24S8U
R3ZPZXH0DA
1YOJE8760X
LSLS7E9TH4
LPCV7UVH32/////// Second Time Generated Strings (After Restart The Application) ///////
F98ER24S8U
R3ZPZXH0DA
1YOJE8760X
LSLS7E9TH4
LPCV7UVH32Please help me to solve my problem.
Thanks in advance.@Ketan__Patel__0011 Sounds like you forgot to initialise the random generator
std::srand(std::time(nullptr)); // use current time as seed for random generator