如何使用cout打印0x0a而不是0xa? [英] How can I print 0x0a instead of 0xa using cout?

查看:360
本文介绍了如何使用cout打印0x0a而不是0xa?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#include  <iostream>
#include  <iomanip>

using namespace std;

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






如果你生病了厌倦了iostream的格式化怪癖,试试 Boost.Format 。它允许使用老式的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\n") % 10;
}

这篇关于如何使用cout打印0x0a而不是0xa?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆