C++ char转换为int(char to int )「终于解决」

C++ char转换为int(char to int )「终于解决」1.通过ascii码:chara=’0′;intia=(int)a;/*notethattheintcastisnotnecessary–intia=awouldsuffice*/cout<<ia<<endl;结果如下:可以看出这种方法得到的其实是char对应的ascii码。因为ascii码…

1.通过ascii码:

char a = '0';
int ia = (int)a; 
/* note that the int cast is not necessary -- int ia = a would suffice */
cout<<ia<<endl;

结果如下: 

C++ char转换为int(char to int )「终于解决」

可以看出这种方法得到的其实是char对应的ascii码。

 

因为ascii码的数字(0)从48开始,所以可以再通过这行代码得到我们想要的数:

int x = ia - 48;
cout<<x;

结果如下:

 C++ char转换为int(char to int )「终于解决」

 

2.直接转换(更简单,推荐) 

char a = '0';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */

结果: 

C++ char转换为int(char to int )「终于解决」 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10771.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注