C++ char vector addition

2019-09-02 09:49发布

问题:

This is a part of a program that I am writing to compute the addition of two integers as strings. (Writing my own bigInt class).

There appears to be a problem when I am adding the two integers together. Because they are both in vectors of char type, I had to add a '0' to each element of the vector before concatenating it into a string.

However, the results are still not what I am expecting:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    string const Number = "1000";
    string const Number2 = "1000";
    vector<char> reverse;
    vector<char> reverse2;

    //cout << (rostrNumber[1] - '0') << endl;
    cout << "Original Number: " << Number << endl;
    reverse.clear();
    for (int i = Number.size() - 1; i >= 0; i--)
    {
        reverse.push_back(Number[i]);

    }
    cout << "Reversed: " << endl;
    cout << reverse[0] << reverse[1] << reverse[2] << reverse[3] << endl;
    cout << endl << endl;

    reverse2.clear();
    {
        for (int i = Number2.size() - 1; i >= 0; i--)
        {
            reverse2.push_back(Number[i]);
        }
    }

    cout << "Adding these two integers" << endl;

    vector<char> const rcvN1 = reverse;
    vector<char> const rcvN2 = reverse2;
    vector<char> Results;

    Results.clear();

    //Local copies
    vector<char> vN1 = rcvN1;
    vector<char> vN2 = rcvN2;
    int iSize1 = vN1.size();
    int iSize2 = vN2.size();
    int i, iSize = iSize2;

    int iC = 0, iR;
    for (i = 0; i<iSize; i++)
    {
        iR = vN1[i] + vN2[i] + iC;

        if (iR > 9)
        {
            iR -= 10;
            iC = 1;
        }
        else
            iC = 0;

        Results.push_back(iR);
        cout << Results[0] << endl;
    }

    if (iC > 0)
        Results.push_back(iC);

    string ostr;
    vector<char>::const_reverse_iterator rIter = Results.rbegin();
    for (; rIter != Results.rend(); rIter++)
        ostr += *rIter +'0';

    cout << "Results: " << ostr << endl;

    system("PAUSE");
    return 0;
}
标签: c++ vector