1

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.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

1 Answers1

2

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.

Mario Rossi
  • 7,651
  • 27
  • 37
  • That explains the reason it yields the same result all the time, however I'm running into this error: variable 'QTime now' has initialized but incomplete type. I've added that code in right above my while loop (is the the right place to put it?) – Barry Michael Doyle Feb 27 '15 at 23:23
  • 2
    You probably need to `#include ` . RE your other comment, you can seed `qrand` every time, but you don't really need to. Once seeded this (or a similar) way, the complete random number sequence will be different every run for all practical purposes. So, you just need to seed once at the beginning of the program. – Mario Rossi Feb 28 '15 at 00:13
  • That worked thanks, still getting the hang of this whole Qt Library – Barry Michael Doyle Feb 28 '15 at 06:45