0

I have an issue which somehow in years of using Qt has not appeared until now.

QString message = "working";
QString a = QString("here is a %1 message. %2!").arg(message).arg("yay");
printf("%s\n",qPrintable(a));

Obviously works fine.

But this will not:

QString message("bad (%1)");
QString b = QString("here is a %1 message. %2!").arg(message).arg("oh no");
printf("%s\n",qPrintable(b));

Since the first string in my case is dynamically coming from another place (namely a percent-encoded url), I am led to think that I will need to escape the incoming arg value, which seems simple enough, although "%%" and "\%" don't do it, so I'm still looking for a way.

But this is a little unsatisfying, as any string coming from any place being used to create a new QString using arg() may do a bad replacement if the content of an earlier arg() happens to have a '%\d' in it.

I admit, after years of using QStrings it hasn't happened until now, but the mechanism calls some of my code into question.

Is there a more recommended approach than just escaping inputs to arg()? This will mean that I will have to sprinkle escapes all over my code base to cover a situation that happens .00001% of the time.

Or rather, %1 of the time. :)

Eyelash
  • 1,760
  • 2
  • 12
  • 18

1 Answers1

0

This is the preferred method as long as you don't have more than 9 replacements:

https://doc.qt.io/qt-5/qstring.html#arg-14

This is the non-recursive method, but won't work with non-QString types, like if arg4 is an int.

In that case, I am opting to convert the int to a QString::number().

Eyelash
  • 1,760
  • 2
  • 12
  • 18