std::cout 给出了来自 qDebug 的不同输出

std::cout gives different output from qDebug

本文关键字:qDebug 输出 cout std      更新时间:2023-10-16

我正在使用Qt,我有一个unsigned char *bytePointer,想打印出当前字节的数字值。下面是我的代码,旨在给出我从连接到计算机的计算机接收的连续字节的 int 值和十六进制值:

int byteHex=0;
byteHex = (int)*bytePointer;
qDebug << "n  int: " //this is the main issue here. 
          << *bytePointer;
std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")n";
}

这给出了完美的结果,我得到了实际的数字,但是这段代码将进入一个API,我不想使用仅限Qt的函数,例如qDebug。所以当我尝试这个时:

int byteHex=0;
byteHex = (int)*bytePointer;
std::cout << "n  int: " //I changed qDebug to std::cout
          << *bytePointer;
std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")n";
}

输出确实完美地给出了十六进制值,但是整数值返回符号(如 ☺ 、└、§,列出一些)。

我的问题是:如何让std::cout给出与qDebug相同的输出?

编辑:由于某种原因,符号仅在特定的Qt设置下出现。我不知道为什么会发生这种情况,但现在已修复。

正如其他人在评论中指出的那样,您将输出更改为十六进制,但实际上并没有在此处设置它:

std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")n";

之后您需要应用以下内容:

std::cout << std::dec;

标准输出流会将任何字符类型输出为字符,而不是数值。若要输出数值,请转换为非字符整数类型:

std::cout << int(*bytePointer);