Create a random string or number in Qt4

Viewed 52073

Is there any function or something like that by which I can create totally random strings or numbers?

7 Answers

Use QUuid

#include <QUuid>
QString randomStr = QUuid::createUuid();

Works in Qt6

double value= QRandomGenerator::global()->bounded(0, 10);

Generate a double from 0 to 10

Here is the good answer using qrand(). The solution below uses QUuid, as already was suggested above, to generate random and unique ids (they are all hex numbers):

#include <QApplication>
#include <QDebug>
#include <QRegularExpression>
#include <QUuid>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // random hex string generator
    for (int i = 0; i < 10; i++)
    {
        QString str = QUuid::createUuid().toString();
        str.remove(QRegularExpression("{|}|-")); // if you want only hex numbers
        qDebug() << str;
    }

    return a.exec();
}

Output

"479a494a852747fe90efe0dc0137d059"
"2cd7e3b404b54fad9154e46c527c368a"
"84e43735eacd4b8f8d733bf642476097"
"d7e824f920874f9d8b4264212f3bd385"
"40b1c6fa89254705801caefdab5edd96"
"b7067852cf9d45ca89dd7af6ffdcdd23"
"9a2e5e6b65c54bea8fb9e7e8e1676a1a"
"981fa826073947e68adc46ddf47e311c"
"129b0ec42aed47d78be4bfe279996990"
"818035b0e83f401d8a56f34122ba7990"
Related