简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM