PDA

View Full Version : doubt in random generated in qt



iswaryasenthilkumar
8th July 2015, 16:01
i getting sequence random number when opening closing and opening the app.My code below:
int Widget::GetRandomString()
{
QString possibleCharacters("0123456789");
int randomStringLength = 4;
QString randomString;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);

}
QFile newfile(PASSCODEFILEPATH);
if (!newfile.open(QIODevice::ReadWrite))
{
return FAIL;
}
QTextStream out(&newfile);
out << randomString.toInt();
newfile.close();
}
i getting the output:
3781
7983
1267
9819
1307
5578
..
i getting these output only,,i need if i run the app output should like 3756 and close the app again open tha app output should be different from previous output.please QT Expered guide me to get proper result,
Thanks in advance:)

wysota
8th July 2015, 16:29
You need to set a different seed for the number generator each time you start your application.

http://en.cppreference.com/w/cpp/numeric/random

Lesiok
8th July 2015, 16:36
Somewhere at the beginning in main() put this line :
qsrand(QDateTime::currentDateTime().toTime_t());