adding string

I want to sum two big integers, and I wrote a code but this code is not working. Can you help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
	string num1 = "123456789098765325235252352352352352323235464645656786786744344534242346688";
	string num2 = "324232523523346574745745645645555555555555555555555456456455457455555555555";
	int temp1 = 0, temp2 = 0;
	int len = num2.length();

	if (num1.length() > num2.length()) {
		len = num1.length();
	}
	int sum = 0;
	string result="";
	int k = 0;
	for (int i = len-1; i >= 0 ; i--) {
		temp1 = num1[i] - '0';
		temp2 = num2[i] - '0';
		sum += temp1+temp2;
		if (sum >= 10) {
			result[k]=(sum%10);
			k++;
			sum = sum % 10;
		}
		else {
			result[k] = sum;
			k++;
			sum = 0;
		}
	}
	len = result.length();
	k = len;
	string result1 = "";
	for (int i = 0; i < len; i++) {
		result1[i] = result[k];
		k--;
	}
	cout << result1;
}
Last edited on
• For both your result and result1 variable, you declare them as empty strings, but then you assign result[k] and result1[i]. This goes out of bounds, because result has 0 characters.

Everywhere that you have result[k] =, you should do result += instead. I think. This might not make it 100% correct yet, but at least you might be printing something now.

• Line 24: You are attempting to assign an integer (sum%10) to a character (result[k]). Perhaps you want (sum%10) + '0';

• Also, you assign k to be the length of result, but then you attempt to access result[k]. This is going out of bounds of the array (although in the case of an std::string, will produce a nullptr for result[result.length()]).

I suggest having better variable names. The difference between "result" and "result1" is not clear at a glance.
I also suggest starting with a smaller example.
e.g. First make sure "4" and "5" produces "9". Then see if "4" and "7" produces "11". Then work with 2-digit numbers, and so on.
Last edited on
Thank you, for your answer.
Topic archived. No new replies allowed.