麦田

不积跬步无以至千里.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

【写在前面】
qDebug 和 QString 算是Qt中最常用也最好用的工具了。

然鹅今天在使用它的时候,遇到了一些非常奇怪的问题。

结果实际上这个坑是 qDebug 导致,所以也不能全怪 QString。

【正文开始】
首先,我们来看一段代码:

#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <iostream>

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

QString dir = app.applicationDirPath();
dir = QDir::toNativeSeparators(dir);

qDebug() << "qDebug:" << dir;
std::cout << "cout: " << dir.toStdString() << std::endl;
printf("printf: ");
for (auto ch : dir) {
printf("%c", ch.toLatin1());
}

return app.exec();
}
猜猜看,这段代码会输出什么?

如果你以为三个输出是一样的,那么恭喜你,你被坑了。

实际上,它们的输出如下:

 

仔细观察,cout 和 printf 是一样的,唯独 qDebug() 输出了一些额外的东西。

我们来看文档中 QDebug &QDebug::operator<<(const QString &t) 的描述:

Writes the string, t, to the stream and returns a reference to the stream. Normally, QDebug prints the string inside quotes and transforms non-printable characters to their Unicode values (\u1234).

To print non-printable characters without transformation, enable the noquote() functionality. Note that some QDebug backends might not be 8-bit clean.

翻译:将字符串t写入流,并返回对该流的引用。 通常,QDebug在引号中打印字符串,并将不可打印的字符转换为它们的Unicode值 (\u1234)。

要在不进行转换的情况下打印不可打印的字符,请启用 noquote() 功能。 请注意,某些QDebug后端可能不是8位干净的。

事实上,qDebug() 不仅会在引号中打印字符串、转换 Unicode,还会完整打印转义字符,例如:\\ \" \t \n 等等。

当然这样做在很多时候是有好处的,毕竟为了方便调试嘛( 调试利器 ),但在某些时候,也会让你陷入坑里。

这样可能导致什么问题?
例如,某些时候你需要一个这样的字符串( 当然这不常见 ):D:\\program\\FFMpeg\\test\\debug,于是你使用 qDebug() 打印一看,嗯?不错,就是这个了。

然鹅实际上,它是 D:\program\FFMpeg\test\debug ,但你并不知晓,然后你接着用,这样最后就可能引发一些的问题,并且还会埋怨 QString 是不是有毛病( 就像我一样呵呵呵呵||ヽ(* ̄▽ ̄*)ノミ )。

那么,如何使用 qDebug() 输出正确的字符串?
答案是 noquote():

#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <iostream>

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

QString dir = app.applicationDirPath();
dir = QDir::toNativeSeparators(dir);

qDebug().noquote() << "qDebug:" << dir;
std::cout << "cout: " << dir.toStdString() << std::endl;
printf("printf: ");
for (auto ch : dir) {
printf("%c", ch.toLatin1());
}

return app.exec();
}
结果如下:

 

文档中 noquote() 的说明如下:

Disables automatic insertion of quotation characters around QChar, QString and QByteArray contents and returns a reference to the stream.

When quoting is disabled, these types are printed without quotation characters and without escaping of non-printable characters.

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

当禁用 quote 时,这些类型的打印将不带引号字符,也不会转义不可打印的字符。

【结语】
很多时候,我们确实享受着Qt带来的各种便利。

但是偶尔,稍不留意,这些便利可能也会坑你一把。

所以,编程还需谨慎啊~
————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/u011283226/article/details/101382747

posted on 2025-06-05 11:08  一些记录  阅读(196)  评论(0)    收藏  举报