How to add two numbers as a string

I need to read two numbers from standard input as strings, in C. How can I print their sum as a string? I have:

char a[10],b[10];
printf("enter the two numbers");
scanf("%s%s",&a,&b);
char sum[20];
sum=?

      

Small tip please? Thank!

+3


source to share


5 answers


chars

- 8-bit binary numbers like less ints

. We have to interpret them to give them meaning as letters.

Your computer may be using the ASCII standard. In ASCII, the value char

representing a character 0

does not actually have a numerical value of 0. It is 48. Fortunately, the numbers are all sequential, so it 1

is 49, and so on.

char zero = '0';
printf("%d\n", zero);
char one = '1';
printf("%d\n", one);

> 48
> 49

      

(Note that the format flag %d

in printf

means "interpret as an integer".)



Since they chars

are numbers, we can do math with them.

char one = '1';
int one_num = one - '0';
printf("%d\n", one_num);

> 1

      

Now you can implement decimal complement and carry over just like on paper.

+1


source


Do it with programming just as you would on paper. Take small steps and make every little step explicitly we take on paper without noticing.

    00111
 ---------
     12345
 123456789
 ---------
 123469134

      



  • Note the different lengths. You will need separate vars to store this information. You will need to find out two lengths, either use a standard function or write your own: strings are binary-terminated 0

    .
  • Notice how we go back as we add. You will need to maintain two indices to access two strings (character arrays).
  • Notice how we carry over the top digit of addition 5+9=14

    . You will need to maintain this in another variable.

Use loops. Once you've added, you'll need to find out the total length and move it to the left edge. Since we don't know in advance how long we will get, you will start writing your answer from the right edge of your array sum

. Think about how and what you can improve on this.

+2


source


If it is not prohibited, I would approach the following:

+2


source


Convert strings to numbers with atoi

, then add them together and then print the sum using a print function like printf. See this

+1


source


Just do it like you did in elementary school

Let's say that the entrance was "... 69 + ... 63"

9 + 3     = 2 and 1 to go
6 + 6 + 1 = 3 and 1 to go
...

      

+1


source







All Articles