構造QString
在 Qt 中如何構造一段格式化字符串?
當然,C 中的方法都是可行的,比如 stdio.h 裏面的 snprintf 什麼的。在 Qt 中QString 提供了更好用的函數。
- arg
這個函數的具體聲明不寫了,它有20個重載,典型的示例代碼如下:
1: #include <QtCore/QCoreApplication>2: #include <iostream>3: #include <stdio.h>4: using namespace std;5:
6: int main()7: {
8: QString str = QString("Ggicci is %1 years old, and majors in %2.").arg(20).arg("Software Eng");9: cout << str.toStdString() << endl;
10: return 0;11: }
輸出結果:Ggicci is 20 years old, and majors in Software Eng.Press <RETURN> to close this window...
上面代碼中的字符串 “Ggicci is %1 years old, and majors in %2.” 中的 %1 和 %2 爲佔位符,後面跟隨的兩個 arg() 函數中的參數分別對應兩個佔位符作爲值插入。這種形式在 C# 中也有類似的體現(C#中輸出一段文字):
Console.WriteLine("Ggicci is {0} years old, and majors in {1}.", 20, "Software Eng");
- sprintf
-
QString & QString::sprintf ( const char * cformat, ... )
這個函數和 C 中的也是差不多的用法,只不過它作爲QString的一個成員函數,使用起來就相當方便了,如:
1: #include <QtCore/QCoreApplication>
2: #include <iostream>
3: #include <stdio.h>
4: using namespace std;
5: int main()
6: {
7: QString str2;
8: str2.sprintf("Ggicci is %d years old, and majors in %s.", 20, "Software Eng");
9: cout << str2.toStdString() << endl;
10: return 0;
11: }
輸入結果:
Ggicci is 20 years old, and majors in Software Eng.Press <RETURN> to close this window...
qDebug()用法
首先在頭文件中包含#include <QDebug>
在需要使用的地方插入:
qDebug("intensity:%d",intensity[0][2]); (%d表示整數)
輸出結果:
intensity:195
qDebug使用形式:
1、qDebug()<<
如:
int nDebug;
QString strDebug;
qDebug()<< "This is for debug, nDebug="<<nDebug<<", strDebug="<<strDebug;
2、qDebug(字符串格式,格式替換實際值)
qDebug("This is for Debug, nDebug=%n, strDebug=%s", nDebug, QByteArray(strDebug.toLatin1).data());
%% 讀%符號