Reputation: 21
int l, s, j, k, carry=0;
string num1, num2, sum;
cin >> num1 >> num2;
l = num1.size();
s = num2.size();
for(j=l-1; j>=0; j--)
{
k = (num1[j]-'0') + (num2[j]-'0') + carry;
cout << k<<endl;
carry = k/10;
k%=10;
sum[j]= '0' + k;
}
cout << sum << endl;
I am trying to add two numbers(both have same digit length) using strings. It is not giving any output.
Upvotes: 1
Views: 95
Reputation: 6440
Just after the variable declaration your sum
variable is an empty string. You're trying to access j
th element of it - this is the array index overflow and is an undefined behavior.
The solution is to initialize your string with something or use concatenate instead of changing the character, like this:
sum += (char)('0' + k);
UP: Such fix will write the result to the string in the reversed order, so, to obtain the correct string, you should also add
std::reverse(sum.begin(), sum.end());
after the loop.
And also, your code assumes that the sum
length is exactly the same as the lengths of both arguments which may be wrong.
Upvotes: 4