Search code examples
ccharascii

how to add char type integer in c


This is the sample code of my program, in which i've to add two string type integer (ex: "23568" and "23674"). So, i was trying with single char addition.

char first ='2';
char second ='1';

i was trying like this..

i=((int)first)+((int)second);
printf("%d",i);

and i'm getting output 99, because, it's adding the ASCII value of both. Anyone please suggest me, what should be the approach to add the char type number in C.


Solution

  • Since your example has two single chars being added together, you can be confident knowing two things

    1. The total will never be more than 18.
    2. You can avoid any conversions via library calls entirely. The standard requires that '0' through '9' be sequential (in fact it is the only character sequence that is mandated by the standard).

    Therefore;

    char a = '2';
    char b = '3';
    
    int i = (int)(a-'0') + (int)(b-'0');
    

    will always work. Even in EBCDIC (and if you don't know what that is, consider yourself lucky).

    If your intention is to actually add two numbers of multiple digits each currently in string form ("12345", "54321") then strtol() is your best alternative.