Maybe this is easy but I am starting on this and would like to pass a char
to int
in c ++
I found a answer in SO in English that I found interesting if you're looking to make it c ++ but for c would also be valid.
You can use the fact that the character encodings for the digits are in order from 48 (for '0') to 57 (for '9'). This is true for ASCII, UTF-x and virtually all other encodings (see comments below for more information on this).
Therefore, the integer value for any digit is the digit minus "0" (or 48).
char c = '1';
int i = c - '0'; // i es ahora igual a 1, no '1'
is the same as
char c = '1';
int i = c - 48; // i es ahora igual a 1, no '1'
However, I find the first c - '0' much more readable.
Also, if you want to make sure that the character to be converted is a digit before converting, you can use the function isdigit
char c = '1';
int a = isdigit(c);
if(a==0){
//no es un digito
}else{
//es digito
c = '1';
int i = c - '0';
}
On the other hand there is the atoi function that allows you to pass a string of characters to int:
char *num = "1024";
int val = atoi(num); // atoi = ASCII TO Int