简体   繁体   中英

Turning a string character into an int

Basically, I have this really long string full of digits:

char *number = "insert really long number";

Now I want to perform math operations on individual digits contained in this string, let's say the following (summing two consecutive digits in this string aka array of chars):

sum = number[i] + number[i+1];

However, this does not produce the correct result, it returns a garbage value. I know how to extract a single value with printf for example:

printf("%c", number[i]);

But how can I get this %c to use in computations as above? I tried with atoi , but I get "error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with &".

1) atoi accept string rather than single character

2) If you want to convert just one ACSII char 0 - 9 just use following code:

if(rChar >= '0' && rChar <= '9')
    val = rChar - '0';

You probably want this:

 char *number = "123";

 int n = 0;
 char c;
 for (int i = 0; c = number[i]; i++)
 {
   n += number[i] - '0';
 }

 printf("n = %d\n", n);

For any number which is represented as a datatype char, you can subtract that number from '0' to get that number in integer type.

For example:

char a = '5';
int num = a - '0';
//num will store 5

Why this works?

Because if you check the ASCII value for '5', it is 53 and for '0' it is 48. So the difference is 5. This will work for converting any number in character form to integer.

The ASCII value for '0' is 48, for '1' it is 49 and so on. So the subtraction from '0' results in giving us the difference of ASCII values.

Here is a link to ASCII values: http://www.asciitable.com/

atoi convert string ( const char* ) to int , if you give it a char it will not work. A solution to convert a char to an int is to use the ASCII table:

char c = '9'
int v = c - '0'; // v == 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM