Convert char to int in C and C++
如何在C和C ++中将char
转换为int
?
Depends on what you want to do:
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 */
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 */
C and C++ always promote types to at least int
. Furthermore character literals are of type int
in C and char
in C++.
You can convert a char
type simply by assigning to an int
.
char c = 'a'; // narrowing on C
int a = c;
Well, in ASCII code, the numbers (digits) start from 48 . All you need to do is:
int x = (int)character - 48;
链接地址: http://www.djcxy.com/p/24568.html
上一篇: 为什么#include <string>可以防止堆栈溢出错误?
下一篇: 在C和C ++中将char转换为int