[Qt-interest] "%" characters in QStrings create havoc

Julien Cugnière julien.cugniere at gmail.com
Fri Feb 26 18:53:29 CET 2010


2010/2/26 KC Jones <kc at asperasoft.com>:
> Using "%%" does indeed appear to solve the parameter substitution problem.
> In my test app the substitutions are predictable and correct.  But it leaves
> me with double %% where I just want %.  I suppose there is no effective
> difference in terms of SQL results between a (b LIKE '%%x%%') and (b LIKE
> '%x%') operation, but I'm not entirely sure about that, and besides, it just
> seems wrong to live with this mess.

"%%" is not documented, because arg() does nothing with it. Scott was
probably thinking of printf-like functions. I don't think there's a
way of escaping %1 in a string.

However, the behavior of QString::arg() is supposed to be well
defined, as long as sufficient place markers are present in the string
(which is your case). I think you should give us some concrete example
of something you consider incorrect so we can look at it.

I suppose the problem you have is the following :

  QString s = QString("%1 OR %2").arg("%1").arg("abc"); // s = "abc OR %2"

This is because the two substitutions are done one after the other.
This is equivalent to :

  QString tmp = QString("%1 OR %2").arg("%1"); // tmp = "%1 OR %2"
  QString s = tmp.arg("abc"); // s= "abc OR %2"

In your case, you should do it in one step, with a single call to
arg() (only possible with string arguments) :

  QString s = QString("%1 OR %2").arg("%1", "abc") // tmp = "%1 OR abc"

If you can't do it in one step, then you have to construct your string
differently (using concatenations, for example).

> It also does not cure my crash in my main application -- which does not
> involve my logging classes as I previously claimed.  In my app, this line
> causes a crash all by itself:
>
> QString clause = QString(" WHERE (name LIKE '%1') OR (email LIKE '%2') ")
>                     .arg(exp1).arg(exp2);

As far as I can tell, QString::arg() is not supposed to crash, no
matter what you throw at it. At worst you'll have a qWarning saying
"QString::arg: Argument missing: ... ".

So, unless there is a bug in QString::arg (which I doubt), I'd say the
crash is coming from somewhere else (memory corruption ?).

-- 
Julien Cugnière




More information about the Qt-interest-old mailing list