简体   繁体   English

std::copy 原始数据使用 ostream_iterator 以十六进制格式复制到 cout<uint8_t> 打印出未格式化的数据。 为什么?

[英]std::copy raw data to cout in hex format using ostream_iterator<uint8_t> prints out unformatted data. Why?

The idea is to have a vector containing arbitrary binary data and outputting the bytes it contains to stdout in hexadecimal notation.这个想法是有一个包含任意二进制数据的向量,并将它包含的字节以十六进制表示法输出到 stdout。 I use std::copy to copy the bytes from the input vector to stdout.我使用 std::copy 将字节从输入向量复制到 stdout。 The problem is that the code prints out 0 followed by raw binary data.问题是代码打印出 0 后跟原始二进制数据。 Here is the code:这是代码:

auto vec = std::vector<uint8_t> {'h', 'e', 'l', 'l', 'o'};
std::cout << std::hex << std::setfill('0') << std::setw(2);
std::copy(vec.begin(), vec.end(), std::ostream_iterator<uint8_t>(std::cout));

The application prints out "0hello".应用程序打印出“0hello”。 I would expect it to print out "68656C6C6F".我希望它打印出“68656C6C6F”。 What can be the case?可能是什么情况?

Simple change, use int instead of uint8_t :简单的改变,使用int而不是uint8_t

std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout));

If you want it in uppercase, use std::uppercase .如果您想要大写,请使用std::uppercase

operator<< has non-member overloads for char , signed char , and unsigned char . operator<<具有charsigned charunsigned char 非成员重载 See: uint8_t iostream behavior .请参阅: uint8_t iostream 行为

Simply replace std::cout in只需将std::cout替换为

std::ostream_iterator<uint8_t>(std::cout)

with std::cout<<std::hex and uint8_t with intstd::cout<<std::hexuint8_tint

std::ostream_iterator<int>(std::cout<<std::hex)

This works because << operator returns reference to the modified stream, which is passed further to the iterator.这是有效的,因为<<运算符返回对修改后的流的引用,该流被进一步传递给迭代器。 Also you can combine it with other modificators such as std::showbase , eg您也可以将其与其他修饰符结合使用,例如std::showbase ,例如

std::ostream_iterator<int>(std::cout<<std::showbase<<std::hex, " ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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