bpat
bpat

Reputation: 1

How do I concatenate char in an array and then add that value to another concatenated array in C?

I have two arrays:

char A[]={1,2,3};

char B[] = {3,4,5};

and I want to get '123' and '345' and then add these two values together. How would I do that?

Upvotes: 0

Views: 51

Answers (1)

Deep Hakani
Deep Hakani

Reputation: 198

Use this code

 #include<stdio.h>
 int stringToInt(char[] );
 int main(){

char A[]={1,2,3};

char B[] = {3,4,5};

 int value_a,value_b,ans;

value_a = stringToInt(A);
value_b = stringToInt(B);
ans = value_a + value_b ;
printf("ANS : %d",ans );

return 0;
}

int stringToInt(char str[]){
int i=0,sum=0;

while(str[i]!='\0'){
     if(str[i]< 48 || str[i] > 57){
         printf("Unable to convert it into integer.\n");
         return 0;
     }
     else{
         sum = sum*10 + (str[i] - 48);
         i++;
     }

}

return sum;

}

Upvotes: 1

Related Questions