Adding two numbers in string array

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


i have an array with numbers but they are characters not integers.
and i want to add

 
array[1] + array[2];

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

i already made the program to check for invalid inputs.

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.
1
2
3
4
5
int total=0;
int end=2;
for(i=0;i<end;i++)
total+ =a[i];
cout<<total;//prints 3 

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
1
2
3
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
1
2
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:
1
2
3
int a =1 ,b=2;
char array[2]={a,b};
cout<<array[0] + array[1]<<endl;//prints 3;QED 
Topic archived. No new replies allowed.