【问题标题】:std::cout reading garbage from a vector when printf reads properly?当 printf 正确读取时,std::cout 从向量中读取垃圾?
【发布时间】:2017-03-26 15:36:40
【问题描述】:

在这段代码中:

// read bootrom
std::ifstream bootrom_file (bootrom_path, std::ios::binary | std::ios::ate);
const int bootrom_size = bootrom_file.tellg();
bootrom_file.seekg(0, std::ios_base::beg);
// allocate bootrom_size bytes for the bootrom vector
bootrom.resize(bootrom_size);
if(bootrom_size != 0x100)
{
    std::cerr << "boot ROM is not 256 bytes!\n";
}
if(bootrom_file)
{
    bootrom_file.read(reinterpret_cast<char*>(bootrom.data()), bootrom_size);
}
// prints 0xC3 0x31
printf("%#02x  %#02x\n", rom[0], bootrom[0]);
// prints ?  1
std::cout << std::hex << rom[0] << "  " << std::hex << bootrom[0] << "\n";

std::cout 打印出来? 1,但 printf 打印出 0xC3 0x31 这是正确的。我在这里做错了什么?

请注意,rom 和 bootrom 都是 uint8_t 的 std::vector,并且 rom 使用与 bootrom 相同的代码设置。

【问题讨论】:

  • romchar 数组吗?试试(int)rom[0]
  • 我在其中添加了它是一个向量 uint8_t
  • 很可能你有类似typedef unsigned char uint8_t; 这样cout 打印字符。
  • 我没有,uint8_t 是在标准中定义的(虽然是字符,是的)。我刚刚得知这就是原因,谢谢。它打印出 ascii 字符。

标签: c++ c++11


【解决方案1】:

解决方案:我想通了。原来 std::cout 不能按值打印 uint8_t 因为它是 typedef char,所以它打印的是 ascii 字符。

【讨论】:

  • 只需将其转换为打印为数字的东西。
  • 显然我已经这样做了,这就是为什么我刚刚宣布最初的问题是什么;即我解决了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多