如何使用 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/