为什么QString印有引号?

时间:2015-01-16 02:54:23

标签: qt qstring qdebug

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

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

我知道我们可以使用qPrintable(const QString)来解决这个问题,但我只是想知道为什么QString会像那样工作?并且QString中是否有一个方法可以改变它的打印方式?

4 个答案:

答案 0 :(得分:24)

Qt 5.4有一项新功能,可让您禁用此功能。引用the documentation

  

QDebug&amp; 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;

另一种选择是将QTextStreamstdout一起使用。在the documentation中有一个例子:

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

答案 1 :(得分:12)

为什么?

这是因为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,则需要引号"来指定类型。

答案 2 :(得分:2)

Qt 4:如果字符串只包含ASCII,则以下解决方法有助于:

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

答案 3 :(得分:2)

简单地转换为const char *

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