为什么 QString 打印有引号?

Why is QString printed with quotation marks?

所以当你使用qDebug()打印一个QString时,输出中突然出现引号。

int main()
{
    QString str = "hello world"; //Classic
    qDebug() << str; //Output: "hello world"
    //Expected Ouput: hello world
}

我知道我们可以用 qPrintable(const QString) 解决这个问题,但我只是想知道为什么 QString 会那样工作?QString 中是否有方法可以改变这种方式打印出来了吗?

为什么?

因为执行了qDebug().

来自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(); }

因此,

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

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

产出

'H' 
 H 
"Hello"

评论

那么 Qt 为什么要这样做呢?由于qDebug是为了调试,各种类型的输入都会通过qDebug.

变成文本流输出

例如,qDebug 将布尔值打印到文本表达式 true / false:

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

它将 truefalse 输出到您的终端。因此,如果你有一个 QString 存储 true,你需要一个引号 " 来指定类型。

Qt 5.4 有一项新功能,可让您禁用此功能。引用 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().

(强调我的。)

以下是您如何使用此功能的示例:

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

另一种选择是将 QTextStreamstdout 结合使用。 the documentation:

中有一个例子
QTextStream out(stdout);
out << "Qt rocks!" << endl;

Qt 4:如果字符串仅包含 ASCII,以下解决方法会有所帮助:

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

只需转换为 const char *

qDebug() << (const char *)yourQString.toStdString().c_str();

一个衬里没有引号:qDebug().noquote() << QString("string");