gpt4 book ai didi

c++ - 在文本文件中一起打印 hex 和 int

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:15 24 4
gpt4 key购买 nike

我正在尝试使用以下代码在同一文本文件中打印 member[0] 和 member[1] 的十六进制值以及 _records 的整数值:

 std::ofstream myoutputfile;

myoutputfile << std::hex << (int)(unsigned char)_member[0] << ' ';

myoutputfile << std::hex << (int)(unsigned char)_member[1] << ' ';

myoutputfile<<_records << std::endl;

但是这段代码也以十六进制打印 _records。我试过:

myoutputfile<<(int)_records << std::endl;

但它仍然以十六进制打印。

谁能帮忙吗

最佳答案

使用 std::dec 将格式设置回十进制

myoutputfile<< std::dec << _records << std::endl;

如您所见,基本格式说明符粘性,因此无需每次都指定std::hex。您的代码可以重写如下以达到相同的效果。

std::ofstream myoutputfile;
myoutputfile << std::hex
<< (int)(unsigned char)_member[0] << ' '
<< (int)(unsigned char)_member[1] << ' '
<< std::dec << _records << std::endl;

您还可以使用 Boost IO State Savers 自动重置为之前的状态.

#include <boost/io/ios_state.hpp>
#include <ios>
#include <iostream>
#include <ostream>

int main()
{
auto hex_printer = [](std::ostream& os, unsigned char byte) {
boost::io::ios_flags_saver ifs(os);
os << std::hex << static_cast<unsigned>(byte) << ' ';
};

hex_printer(std::cout, 'A');
std::cout << 42 << '\n';
}

Live demo

关于c++ - 在文本文件中一起打印 hex 和 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com