如何使用 cout 打印 0x0a,而不是 0xa?
#include <iostream>
using std::cout;
using std::endl;
using std::hex;
int main()
{
cout << hex << showbase << 10 << endl;
}
这对我在海湾合作委员会有用:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl;
}
如果您厌倦了 iostream 格式的怪异,请给升压格式 http://www.boost.org/doc/libs/1_46_1/libs/format/尝试一下。它允许使用老式的 printf 样式格式说明符,但它是类型安全的。
#include <iostream>
#include <boost/format.hpp>
int main()
{
std::cout << boost::format("0x%02x\n") % 10;
}
更新(2019)
查看{fmt} 库 https://github.com/fmtlib/fmt已被接受进入C++20 https://en.cppreference.com/w/cpp/utility/format/format。基准测试显示它比 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)