1

I have tried to use the example given in the Qt4.8 documentation:

#include <QCoreApplication>
#include <QString>
#include <iostream>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString str;
    str = "%1 %2";

    str.arg("%1f", "Hello");        // returns "%1f Hello"
    std::cout << str.toStdString().c_str() << std::endl;

    str.arg("%1f").arg("Hello");    // returns "Hellof %2"
    std::cout << str.toStdString().c_str() << std::endl;

    return a.exec();
}

However this outputs :

%1 %2

%1 %2

both times. I have tried this on Windows 7 and Ubuntu, using QtCreator and from the command line. I have checked I have

QMake version 2.01a

Using Qt version 4.8.1 in /usr/lib/x86_64-linux-gnu

and in Windows:

QMake version 2.01a

Using Qt version 4.7.0 in C:\qt\4.7.0\lib

I have even checked my source files for non-ascii characters, e.g. the "%" sign is correct. Please tell me why this doesn't work!

Here is the PRO file I am using:

QT       += core

QT       -= gui

TARGET = testarg
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • I'm betting that this example is added to documentation at the bottom of page as notes by community (someone posted code without running it). – Marek R Feb 19 '14 at 13:35

2 Answers2

5

The arg() functions do not modify the QString (if you look at the docs, these functions are const.) They return a new QString instead, which you aren't saving anywhere. If you want to modify the original string, you can do so with:

str = str.arg("%1f", "Hello");

If you want to preserve the original, just use a new QString instead:

QString tmp = str.arg("%1f", "Hello");
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
3
#include <QCoreApplication>
#include <QString>
#include <iostream>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString str;
    str = "%1 %2";

    QString a = str.arg("%1f", "Hello");        // returns "%1f Hello"
    std::cout << a.toStdString().c_str() << std::endl;

    QString b = str.arg("%1f").arg("Hello");    // returns "Hellof %2"
    std::cout << b.toStdString().c_str() << std::endl;

    return a.exec();
}

note all arg overloads are const and return QString :).

Marek R
  • 32,568
  • 6
  • 55
  • 140