c++qtrandomqstringqchar

Generate random QString yields same result every time


I'm working on a QT project where a user inputs their full name and the program generates a random 5 character password based off of the letters in their name. Unfortunate I've run into an issue where it works but every time I rerun the program it yields the same result. So it clearly isn't very random. Even after exiting QT Creator and opening it again and running the program with the same user input it yields the same results.

I also am required to generate the password without spaces.

Here is my code:

while(password.length() < 5) {
        int index = qrand() % fullName.length();
        QChar nextChar = fullName.at(index);
        if (!nextChar.isSpace()) {
            password.append(nextChar);
        }
    }

Any solution would be much appreciated.


Solution

  • You need to provide qrand with a suitable seed (usually at program startup). Try:

    QTime now= QTime::currentTime() ;
    qsrand( now.msec() );
    

    You don't ask about this, but are you checking that fullName's length is not zero (as the program would attempt to divide by zero)? Or that it's not composed of blanks only (as it would loop forever)? A simple solution to both is to trim fullName and check that its length is strictly greater than zero.