printf to show QString



我正在使用QString调试一个程序。我添加了printf来显示QString的内容,但它只显示第一个字母。

代码如下。fprintf是我添加的内容。

QString profilePath = mltPath;
fprintf(stderr, "profilePath: %sn", profilePath.data());

输出为

profilePath: /

profilePath.data()是一个QChar*,它是一个16位unicode字符。https://doc.qt.io/qt-5/qchar.html

转换为constchar*的一个解决方案是使用qPrintable(profilePath)将QString转换为const-char*

QString profilePath = mltPath;
fprintf(stderr, "profilePath: %sn", qPrintable(profilePath));

const char * qPrintable(const QString& str)的文档如下:https://doc.qt.io/qt-5/qtglobal.html#qPrintable

只需使用QString::toUtf8((,例如。fprintf(stderr, "profilePath: %sn", profilePath.toUtf8());

您不应该使用printf,因为它主要用于C中(或者应该是(。

既然您使用的是Qt,为什么不使用QDebug呢?然后你所要做的就是打电话:qDebug() << "profilePath:" << profilePath;

如果您使用QDebug,您还可以获得分类日志记录的优势。

您似乎可以使用toLocal8Bit()方法将其转换为系统上具有本地编码的QByteArray(文档(。

所以你想在你的代码中使用这个:

QString profilePath = mltPath;
fprintf(stderr, "profilePath: %sn", profilePath.toLocal8Bit().constData());

最新更新