Why is QString printed with quotation marks?

99封情书 提交于 2019-11-30 11:50:12

Why?

It's because of the implementation of qDebug().

From the source code:

inline QDebug &operator<<(QChar t) { stream->ts << '\'' << t << '\''; return maybeSpace(); }
inline QDebug &operator<<(const char* t) { stream->ts << QString::fromAscii(t); return maybeSpace(); }
inline QDebug &operator<<(const QString & t) { stream->ts << '\"' << t  << '\"'; return maybeSpace(); }

Therefore,

QChar a = 'H';
char b = 'H';
QString c = "Hello";

qDebug()<<a;
qDebug()<<b;
qDebug()<<c;

outputs

'H' 
 H 
"Hello"

Comment

So why Qt do this? Since qDebug is for the purpose of debugging, the inputs of various kinds of type will become text stream output through qDebug.

For example, qDebug print boolean value into text expression true / false:

inline QDebug &operator<<(bool t) { stream->ts << (t ? "true" : "false"); return maybeSpace(); }

It outputs true or false to your terminal. Therefore, if you had a QString which store true, you need a quote mark " to specify the type.

MrEricSir

Qt 5.4 has a new feature that lets you disable this. To quote the documentation:

QDebug & QDebug::​noquote()

Disables automatic insertion of quotation characters around QChar, QString and QByteArray contents and returns a reference to the stream.

This function was introduced in Qt 5.4.

See also quote() and maybeQuote().

(Emphasis mine.)

Here's an example of how you'd use this feature:

QDebug debug = qDebug();
debug << QString("This string is quoted") << endl;
debug.noquote();
debug << QString("This string is not") << endl;

Another option is to use QTextStream with stdout. There's an example of this in the documentation:

QTextStream out(stdout);
out << "Qt rocks!" << endl;

Qt 4: If the string contains just ASCII, the following workaround helps:

qDebug() << QString("TEST").toLatin1().data();

Simply cast to const char *

qDebug() << (const char *)yourQString.toStdString().c_str();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!