加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用cout将字符显示为十进制数

发布时间:2020-12-16 10:51:34 所属栏目:百科 来源:网络整理
导读:在C编程语言中,我可以使用printf来显示字符及其十进制等效代码,如下所示 char c='e';printf( "decimal value: %d char value: %cn",c,c); 如何使用cout在C中做同样的事情?例如,以下代码显示字符,但如何让cout打印小数值? char c='e';cout c; 解决方法 cou
在C编程语言中,我可以使用printf来显示字符及其十进制等效代码,如下所示

char c='e';
printf( "decimal value: %d   char value: %cn",c,c);

如何使用cout在C中做同样的事情?例如,以下代码显示字符,但如何让cout打印小数值?

char c='e';
cout << c;

解决方法

cout << +c;

一元转换运算符将隐式地将char转换为int.

Demo here

从5.3.1一元运算符aka expr.unary.op

[7] The operand of the unary + operator shall have arithmetic,
unscoped enumeration,or pointer type and the result is the value of
the argument. Integral promotion is performed on integral or
enumeration operands. The type of the result is the type of the
promoted operand.

进一步阅读:

> cppreference > Utilities Library > Type support > std::is_integral了解积分类型的含义.
> cppreference > C++ > C++ Language > Expressions > Implicit conversions>数字促销>整体推广

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读