Pass a char to int in a data structure in c ++

0

Maybe this is easy but I am starting on this and would like to pass a char to int in

    
asked by J Molina 23.05.2017 в 21:49
source

1 answer

2

I found a answer in SO in English that I found interesting if you're looking to make it but for 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
    
answered by 24.05.2017 в 10:15