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;
}
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;
}
UPDATE (2019)
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…