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;

结果如下: 

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

 

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

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

结果如下:

 

 

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

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

结果: 

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐