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

KC Jones kc at asperasoft.com
Fri Feb 26 02:54:09 CET 2010


What is the correct way to place percent characters in QStrings?

I find that QStrings containing '%' characters act erratically and
cause crashes.  I am able to reproduce some erratic behaviours, but so
far I cannot isolate the crashes that I suffer in my application's
logging classes.  What I think is the root of the problem comes from
unwanted, unexpected parameter substitution.

The following code is taken from a test app I put together.  I can
share that as needed. I've fiddled around with escaping the percent
characters, replacing "%" with "\%" and "\\\%" without much success.

When the input string contains '1' or '2', the results in 'clause' are
unpredictable and wrong.  But other characters in the 'str' are also
problematic.

In my application I am constructing SQL WHERE clauses that perform
LIKE searches in which the '%' characters are essential.  The search
can be based on arbitrary user input, so I need to find a bulletproof
way to construct these SQL queries for all possible text input.

void percent::showFilter(const QString &str)
{
    QString exp1 = "%";
    for (int i = 0, im = str.size(); i < im; i++) {
        exp1.append(str[i]).append("%");
    }
    QString exp2 = exp1 + "@%";
    QString clause = QString(" WHERE (name LIKE '%1') OR (email LIKE '%2') ")
                     .arg(exp1).arg(exp2);

    ui->exp1->setText(exp1);
    ui->exp2->setText(exp2);
    ui->result->setText(clause);
}



More information about the Qt-interest-old mailing list