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;
結果如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLzkTOxAjN1QTM0EzMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
可以看出這種方法得到的其實是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 */
結果: