This loop is supposed to add two numbers that are stored in vectors by their individual digits. So, for example leftc will contain [10]{0,9,0,0,0,0,0,0,5,7} and rightc will contain
[10]{0,0,0,0,0,0,0,0,9,6} and at the end of the loop number should contain “0900000153” (leading zeros are stripped off later in the program). It works perfectly until it gets to index = 0 and then it causes an overflow error, but I can’t figure out why.
string number; // accumulates the result of the addition
int num; // holds the result of adding corresponding elements
short carry = 1;
for ( size_t index = leftc.size() - 1; index >= 0; index-- ) // start from the end of the vectors and work toward the beginning
{
num = leftc.at(index) + rightc.at(index); // add the two elements and store in num
if ( num >= 10 )
{
num %= 10;
leftc.at(index - 1) += carry;
}
num += '0'; // convert num from int to char
number.insert( number.begin(), num ); // store num at front of number
}
Any help is greatly appreciated. Thank you!
You have a problem here
As
size_tis unsigned,indexwill always be>=0.