You are using a version without Ads of this website. Please, consider donating:

### Adding two numbers in string array

 `` `` ``string array[2] = {'1','2'};``

i have an array with numbers but they are characters not integers.

 `` `` ``array[1] + array[2];``

so i can get a result of 3
but when i do a cout i get an output of '12'

how can i add these two numbers?
Hi kcbob,

Your array uses data type string.

You would need to convert each string element to an integer.

You could use the library function: atoi()

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

For example:

atoi(array[0].c_str()) would return the integer value of the string element.
first of all, arrays count from 0. That is the first element in an array a is a[0].
Use a loop to add the elements e.g.
 ``12345`` ``````int total=0; int end=2; for(i=0;i

If the contents of the elements are characters initialize a[0] ='a'-96 and a[1]=' b'-96 and use the same loop arrangement.
note:not tested!
im still having some trouble

my string array got its input from
 ``123`` ``````char temp[size] = [1]; // '[' and ']' are characters, assume only 1 digit will be used string array[size]; array[0] = temp[1];``````

so i need array[0] and array[1] to get added
 ``12`` ``````int opr; opr = atoi(string.c_str());``````

as for atoi i get an error saying "`c_str' has not been declared. "
Last edited on
Bump
i can`t understand why you are using a string array to add characters after converting them with atoi() when an int array would add the digits so easily. however if:
 ``123`` ``````int a =1 ,b=2; char array[2]={a,b}; cout<
Topic archived. No new replies allowed.