Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt/c++ random string generation [duplicate]

Tags:

c++

qt

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++?

like image 531
user2444217 Avatar asked Sep 18 '13 02:09

user2444217


People also ask

How do you generate random numbers in Qt?

QRandomGenerator::system() may be used to access the system-wide random number generator, which is cryptographically-safe on all systems that Qt runs on. This function will use hardware facilities to generate random numbers where available.

How do you get a random number between 0 and 1 in C++?

C++ Random Number Between 0 And 1 We can use srand () and rand () function to generate random numbers between 0 and 1. Note that we have to cast the output of rand () function to the decimal value either float or double.

How do you generate random alphanumeric strings in C++?

Example 1: Using the rand() Function to Generate Random Alphabets in C++ The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.

How do you generate a random number in C++?

One way to generate these numbers in C++ is to use the function rand(). Rand is defined as: #include <cstdlib> int rand(); The rand function takes no arguments and returns an integer that is a pseudo-random number between 0 and RAND_MAX.


1 Answers

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;
}
like image 120
TheDarkKnight Avatar answered Oct 16 '22 17:10

TheDarkKnight