我目前正在使用QT中的QStrings,似乎无法理解为什么以下代码对我不起作用。
#include <QCoreApplication>
#include <QDebug>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString test;
int x = 5;
test.append("This is a test of the Arg Function %1").arg(x);
qDebug() << test;
//should output This is a test of the Arg Function 5
return a.exec();
}
我得到的输出是:
这是对Arg函数%1的测试
显然我期待值5替换%1,我错过了一些明显的东西吗?
答案 0 :(得分:4)
您需要test = test.append("This is a test of the Arg Function %1").arg(x);
,因为arg
会返回新字符串。
来自here的示例:
QString i; // current file's number
QString total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
或者像vahancho建议:
test.append(QString("This is a test of the Arg Function %1").arg(x));
Michael Burr建议:
test += QString("This is a test of the Arg Function %1").arg(x);
另一个没有arg
的人:
test.sprintf("This is a test of the Arg Function %d", x);
你可以看看那个人How to format a QString?
答案 1 :(得分:0)
因为您没有阅读有关QString :: arg的文档。它返回字符串的副本。
qDebug() << test.arg(x) - it`s must work