简体   繁体   中英

std::cout reading garbage from a vector when printf reads properly?

In this code:

// 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 prints out ? 1, but printf prints out 0xC3 0x31 which is correct. What am I doing wrong here?

Note that rom and bootrom are both std::vector of uint8_t, and rom is set using the same code as bootrom.

Solution: I figured it out. Turns out that std::cout cannot print uint8_t by value since it is a typedef char, so it prints the ascii character instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM