1

I have an array that is char and all of them are numbers but in type of Char means:

myArray = ['5','6','8','9','10',....]

for example i wnat to add two of them.i must to convert them to integer and then add them together but using:

(int)myArray[1]+(int)myArray[2]

give a wrong answer. what is the function or the correct way for doing this?

user3000968
  • 156
  • 1
  • 7

2 Answers2

5

For ASCII digit chars from '0' - '9', one can substract the value of '0', since their values are contiguous:

char digit = '7' ; //any char, from '0' ... '9'
int value = digit - '0';

Further information: Are the character digits ['0'..'9'] required to have contiguous numeric values?

Community
  • 1
  • 1
Sam
  • 7,778
  • 1
  • 23
  • 49
  • 1
    For **all** encodings this is required. It's just about the only thing that's portable across encodings. – Pete Becker Nov 22 '13 at 18:59
  • @Pete Becker : Thank you for pointing that out. I've read up a bit, starting at the link I added. Until now, I never questioned the portability of my code regarding alphanumeric ranges. – Sam Nov 22 '13 at 19:34
  • I usually thump people for making ASCII-centric assumptions, so I appreciate your caution. – Pete Becker Nov 22 '13 at 20:35
1

You can use the function atoi, for example:

char str[] = "122";
int i = atoi(str);

Notice that you must use the double quotes (") for strings. The single quotes (') work only for characters.

Also, you must add this include:

#include <cstdlib>
jdc
  • 319
  • 2
  • 5