Reputation: 1706
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);
}
Upvotes: 6
Views: 14704
Reputation: 93
I have used the answer by Antoyo myself but I ran into an issue today. digitValue() is not the same as comparing a char in C using atoi like the op Thomas was trying to do. So while Thomas was trying to do this:
for (int i=0; i<path.length(); i++){
char c = path.at(i);
int j = atoi(&c);
//player->movePlayer(direction);
}
with digitValue() it would have become this:
for (int i=0; i<path.length(); i++){
int j = path.at(i).digitValue();
//player->movePlayer(direction);
}
However this does not have the expected results if there are any letters in the string. For example in C, if the string has a mix of Letters and numbers then any char you use atoi on will return a 0 in place of a letter. digitValue() however does not return 0 for a letter. It may be a good idea to do a check for isDigit() first if you have any concerns about letters ending up in your string and the final result would look like this:
int j = 0;
for (int i=0; i<path.length(); i++){
if (path.at(i).isDigit())
j = path.at(i).digitValue();
else
j = 0;
//player->movePlayer(direction);
}
This may not have been a concern for the OP but since this is one of the top Google results for getting numbers from a string in QT it might help someone else, especially if you're trying to get a QT application to behave the same as some embedded C code on a device.
Upvotes: 1
Reputation: 1629
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;
Upvotes: 10
Reputation: 79447
Use QTextStream:
QString str = "123 234 23123 432";
QTextStream stream(&str);
QList<int> array;
while (!stream.atEnd()) {
int number;
stream >> number;
array.append(number);
}
Upvotes: 3
Reputation: 11913
You may get every character (QChar) with the [] operator and use the digitValue() method on them to get the integer.
Upvotes: 4