PDA

View Full Version : Getting an error for QString::arg instead of message



akiross
8th April 2011, 22:14
Hello,
I'm using QString::arg in a dynamical environment: string and arguments are unknown. So I've to replace the place markers as they come.
My problem is that I can get more arguments to replace than markers in the string, so it's probable I'm getting an error. The documentation says:

If there is no unreplaced place marker remaining, a warning message is output and the result is undefined. Place marker numbers must be in the range 1 to 99.

I don't need the warning message, but something I can handle in the code (value or exception). But being the result undefined in case of error, I don't know how to proceed.

Apart the brutal counting of "%X" in the string (which, again, is useless to count as my arguments are dynamic so the count may change in each substitution), is there a way to get an error/exception instead of that warning message?

Thanks.
~Aki

ChrisW67
9th April 2011, 01:16
I think the only way to know ahead of time if the pattern string contains placeholders is to look for one (no need to count them all). Something like this:


#include <QtCore>
#include <QDebug>

QString dynamicReplace(const QString &pattern, const QStringList &values)
{
static QRegExp marker("%\\d\\d?");

QString result = pattern;
QStringListIterator i(values);
while (i.hasNext() && result.contains(marker) > 0)
result = result.arg(i.next());
return result;
}


int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);


QStringList values = QStringList() << "A" << "B" << "C";

qDebug() << "Markers match values:" << dynamicReplace("%1 %2 %3", values);
qDebug() << "More values than markers:" << dynamicReplace("%1 %2", values);
qDebug() << "More markers than values:" << dynamicReplace("%1 %2 %3 %4", values);

values << "value inserts %1 marker or %2" << "D" << "E";
qDebug() << "Marker added on the fly:" << dynamicReplace("%1 %2 %3 %4", values);

return app.exec();
}

akiross
9th April 2011, 11:57
Ok, I was hoping in Qt to have such a method, but I guess it's not the case :)
Thank you very much!
~Aki