在 C 和 C++ 中将 char 转换为 int [英] Convert char to int in C and C++

查看:47
本文介绍了在 C 和 C++ 中将 char 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 和 C++ 中将 char 转换为 int?

How do I convert a char to an int in C and C++?

推荐答案

取决于你想做什么:

以ASCII码形式读取值,可以这样写

to read the value as an ascii code, you can write

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

转换字符'0' ->0, '1' ->1等,可以写

to convert the character '0' -> 0, '1' -> 1, etc, you can write

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

说明:
a - '0' 等价于 ((int)a) - ((int)'0'),意思是每个字符减去ascii值其他.由于 0 在 ascii 表中直接出现在 1 之前(依此类推直到 9),两者之间的差异给出了字符a 代表.

Explanation:
a - '0' is equivalent to ((int)a) - ((int)'0'), which means the ascii values of the characters are subtracted from each other. Since 0 comes directly before 1 in the ascii table (and so on until 9), the difference between the two gives the number that the character a represents.

这篇关于在 C 和 C++ 中将 char 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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