如何使用qDebug打印字符串文字和QString?

时间:2013-08-25 08:44:29

标签: c++ qt qstring qdebug

有没有简单的方法来完成以下工作?我的意思是Qt中有没有为qDebug准备字符串的助手类?

QString s = "value";
qDebug("abc" + s + "def");

6 个答案:

答案 0 :(得分:23)

您可以使用以下内容:

qDebug().nospace() << "abc" << qPrintable(s) << "def";

nospace()是为了避免在每个参数后打印出空格(这是qDebug()的默认值)。

答案 1 :(得分:21)

我并不是很容易理解。你可以这样做:

QByteArray s = "value";
qDebug("abc" + s + "def");

QString s = "value";
qDebug("abc" + s.toLatin1() + "def");

答案 2 :(得分:9)

根据Qt Core 5.6 documentation,您应使用qUtf8Printable()标题中的<QtGlobal>QString一起打印qDebug

您应该执行以下操作:

QString s = "some text";
qDebug("%s", qUtf8Printable(s));

或更短:

QString s = "some text";
qDebug(qUtf8Printable(s));

请参阅:

答案 3 :(得分:6)

选项1:使用qDebug的C字符串格式和变量参数列表的默认模式(如printf):

qDebug("abc%sdef", s.toLatin1().constData());

选项2:使用带有重载的C ++版本&lt;&lt;操作者:

#include <QtDebug>
qDebug().nospace() << "abc" << qPrintable(s) << "def";

参考:https://qt-project.org/doc/qt-5-snapshot/qtglobal.html#qDebug

答案 4 :(得分:3)

只需重写您的代码:

QString s = "value";
qDebug() << "abc" << s << "def";

答案 5 :(得分:1)

我知道这个问题有点陈旧,但在网上搜索时它似乎几乎排在最前面。可以为qDebug(更具体的QDebug)重载操作符,使其接受std :: strings,如下所示:

inline QDebug operator<<(QDebug dbg, const std::string& str)
{
    dbg.nospace() << QString::fromStdString(str);
    return dbg.space();
}

这件事在我的所有项目中都存在多年,我几乎忘记它默认不存在。

之后,使用&lt;&lt;对于qDebug()是更有用的imho。你甚至可以混合使用QString和std :: string。一些额外的(但不是真正意图的)特性是,你有时可以抛出整数或其他允许隐式转换为std :: string的类型。