如何使用 cout 打印 0x0a 而不是 0xa?

2022-01-04 00:00:00 io iostream c++ iomanip

如何使用 cout 打印 0x0a 而不是 0xa?

How can I print 0x0a, instead of 0xa using cout?

#include  <iostream>

using std::cout;  
using std::endl;  
using std::hex;

int main()  
{  
    cout << hex << showbase << 10 << endl;  
}

推荐答案

这对我在 GCC 中有效:

This works for me in GCC:

#include  <iostream>
#include  <iomanip>

using namespace std;

int main()
{
    cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl;
}

<小时>

如果您对 iostream 的格式古怪感到厌烦,请使用 Boost.格式化试试.它允许使用老式的 printf 风格的格式说明符,但它是类型安全的.


If you are getting sick and tired of iostream's formatting quirkiness, give Boost.Format a try. It allows good-old-fashioned, printf-style format specifiers, yet it is type-safe.

#include <iostream>
#include <boost/format.hpp>

int main()
{
    std::cout << boost::format("0x%02x
") % 10;
}

<小时>

更新(2019 年)

查看已被接受的{fmt} 库进入 C++20.基准测试表明它比 Boost.Format 更快.

Check out the {fmt} library that's been accepted into C++20. Benchmarks show it to be faster than Boost.Format.

#if __has_include(<format>)
    #include <format>
    using std::format;
#else
    #include <fmt/format.h>
    using fmt::format;
#endif

std::cout << format("{:#04x}
", 10);

相关文章