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

标签 c++ io iostream iomanip

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

#include  <iostream>

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

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

最佳答案

这在 GCC 中对我有用:

#include  <iostream>
#include  <iomanip>

using namespace std;

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

如果您厌倦了 iostream 的格式怪异,请给 Boost.Format试一试。它允许使用老式的 printf 样式的格式说明符,但它是类型安全的。

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

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

更新(2019 年)

查看 {fmt} library已被接受 into C++20 .基准测试表明它比 Boost.Format 更快。

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

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

关于c++ - 如何使用 cout 打印 0x0a 而不是 0xa?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760252/

相关文章:

c# - 创建后无法立即写入文件

Java:如何将 InputStream 通过管道传输到标准输出?

haskell - 将 Either a (IO b) 转换为 IO (Ei a b)

c++ - 无阻塞地使用c++输入流cin

c++ - getline(cin, string) 即使使用 cin.ignore() 也不起作用

C++ 符号在共享对象中具有不同的大小

c++ - 如何在 ADL 期间使功能模板成为最低优先级?

C++ 错误 : class template has already been defined

c++ - 超快速在线C++评估器

c++ - 使用标准 C++ wifstream 读取 UTF-8 文本并转换为 UTF-16