How can I convert a QString of numbers to an array of int?

Thomas picture Thomas · Jan 5, 2013 · Viewed 12.4k times · Source

I have a QString containing a series of numbers for example

QString path = "11100332001 234 554 9394";

I want to iterate over the variable length string

for (int i=0; i<path.length(); i++){

}

and be able to acces each number as an int individually.

I haven't been able to do so however. Question: How can I convert a QString of numbers to an array of int?

I know I can convert the QString to an int using path.toInt() but that doesn't help me.

When trying to convert it to a char first I get an error: cannot convert 'const QChar to char'.

for (int i=0; i<path.length(); i++){
        char c = path.at(i);
        int j = atoi(&c);
        //player->movePlayer(direction);
    }

Answer

Youssef Bouhjira picture Youssef Bouhjira · Jan 5, 2013

you can use split to obtain an array of substrings separated by the separator you want in this case it's a space , here is an example :

QString str("123 457 89");

QStringList list = str.split(" ",QString::SkipEmptyParts);

foreach(QString num, list)
    cout << num.toInt() << endl;