22

因此,当您使用qDebug()打印 a时QString,引号会突然出现在输出中。

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

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

4

5 回答 5

38

Qt 5.4 有一个新特性可以让你禁用它。引用文档

QDebug & QDebug::​noquote()

禁止在 QChar、QString 和 QByteArray 内容周围自动插入引号字符并返回对流的引用。

这个函数是在 Qt 5.4 中引入的。

另请参见 quote() 和 MaybeQuote()。

(强调我的。)

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

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

另一种选择是使用QTextStreamwith stdout文档中有一个这样的例子:

QTextStream out(stdout);
out << "Qt rocks!" << endl;
于 2015-01-16T03:33:25.623 回答
16

为什么?

这是因为qDebug().

源代码

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

它输出true或输出false到您的终端。因此,如果您有QStringwhich store true,则需要一个引号"来指定类型。

于 2015-01-16T03:23:43.133 回答
6

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

qDebug() << QString("TEST").toLatin1().data();
于 2015-04-16T13:20:45.060 回答
2

只需投射到const char *

qDebug() << (const char *)yourQString.toStdString().c_str();
于 2017-03-06T14:09:22.003 回答
-1

一个班轮没有报价:qDebug().noquote() << QString("string");

于 2021-11-30T13:20:48.047 回答