Cout没有打印号码

时间:2011-11-09 13:31:19

标签: c++ pointers printf cout

问题

我从一个简单的cout没有输出,而printf将始终打印数字:

std::cout << variableuint8;  // prints nothing
printf("%u", variableuint8); // prints the number

我以前从未遇到过这种行为,虽然我有一个解决方法,但我想了解它。

上下文:

是的,指针。所以它可能比所述的更多参与。这是上下文 - 我不认为它应该重要,当cout和printf获取信息时,它被解除引用到一个简单的unsigned char。这可能是解决问题所需的更多信息,但我想完全了解它是否相关。

typedef unsigned char   UInt8;
typedef unsigned short  UInt16;

typedef struct{
   UInt8   len;
   // some other definitions. sizeof(DeviceNotification) <= 8
}DeviceNotification;

UInt8 somerandomdata[8];
DeviceNotification * notification;

notification = (DeviceNotification *) somerandomdata;

std::cout << "Len: (" << notification->len << ")\n";
printf("Len: (%u)\n", notification->len);

随机数据在其他地方初始化。对于此输出,数组中的第一个字节是0x08:

输出:

Len: ()
Len: (8)

环境

  • 开发机器:
    • OS X 10.6.8
    • 编译器LLVM 1.7
    • Xcode 3.2.6
  • 试验机:
    • OS X 10.6.8

3 个答案:

答案 0 :(得分:12)

它将char打印为角色。

#include <iostream>

int main() {
        unsigned char c = 0x41;
        std::cout << c << std::endl;
        return 0;
}

这会将'A'打印到标准输出。

虽然在这种情况下,您的代码应该打印Len: (*),我确实已经验证它打印Len: (*)


编辑:由于您的控制台可能正在使用ASCII或UTF-8这样的字符编码,因此不会看到与8(Backspace)对应的字符,它看起来好像没有打印。

(在某些情况下,它可能会导致前一个字符(()消失,因为它是退格字符。在DOS中它可能显示◘)

答案 1 :(得分:4)

您是否尝试将其强制转换为int,以避免依赖于实现使用的char类型:

std::cout << (int)variableuint8;

以下是对正在发生的事情的解释:What is an unsigned char?

要获得一个想法,您的实施使用unsigned char作为char。 0x08的ASCII代码是退格控制字符,当然它不是可打印的字符,这就是为什么在std::cout的情况下看不到输出的原因。

答案 2 :(得分:3)

std::cout << "Len: (" << (unsigned short)notification->len << ")\n";会打印正确的值吗?我猜可能正在寻找一个整数。

相关问题