7

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
  • 581
  • 2
  • 7
  • 16
  • 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

29

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
  • 5,070
  • 8
  • 48
  • 70
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85