6

I am creating an application where I need to generate multiple random strings, almost like a unique ID that is made up of ASCII characters of a certain length that have a mix of uppercase/lowercase/numerical characters.

Are there any Qt libraries for achieving this? If not, what are some of the preferred ways of generating multiple random strings in pure c++?

user2444217
  • 561
  • 2
  • 7
  • 15
  • 4
    possible duplicate of [Create a random string or number in Qt4](http://stackoverflow.com/questions/3244999/create-a-random-string-or-number-in-qt4) also see [How do I create a random alpha-numeric string in C++?](http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c) – Shafik Yaghmour Sep 18 '13 at 02:45

1 Answers1

28

You could write a function like this:

QString GetRandomString() const
{
   const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
   const int randomStringLength = 12; // assuming you want random strings of 12 characters

   QString randomString;
   for(int i=0; i<randomStringLength; ++i)
   {
       int index = qrand() % possibleCharacters.length();
       QChar nextChar = possibleCharacters.at(index);
       randomString.append(nextChar);
   }
   return randomString;
}
eebbesen
  • 4,946
  • 8
  • 48
  • 68
TheDarkKnight
  • 26,423
  • 4
  • 51
  • 83