I need a little help to store two strings into a vector and reversing the order of each string. i.e.

123456789 needs to be 987654321
12345 needs to be     000054321

reason for that is I need to add those two numbers together.

Edited by VUEKID

4 Years
Discussion Span
Last Post by deceptikon

With C++11 it's super trivial:

vector<string> v{ "123456789", "12345" };
long long result = 0;

for (auto x : v) {
    reverse(begin(x), end(x));
    result += stoll(x);

Of course, you do need to take into consideration whether the summed values will fit in the result. You may want to consider a big number library that allows arbitrary integer lengths.


also, how would I store the strings entered by an user input n not predefined strings?


This is what I have, don't seem to work though.

    string num1; 
    string num2 ; 

    cout << "Enter a large number." << endl; 
    //cin >> num1; 
    std::getline (std::cin,num1);
    cout << "Enter a second large number." << endl; 
    //cin >> num2; 
    std::getline (std::cin,num2);

    const int INIT_VECTOR_SIZE = 20;
    vector <string> words(INIT_VECTOR_SIZE);
    words.push_back( num1 );
    vector <string> words2(INIT_VECTOR_SIZE);
    words.push_back( num2 ) ;

    long long result = 0;
    for (auto x : words) {
    reverse(begin(x), end(x));    result += stoll(x);

your first line's got a error,

I also explicitly stated C++11, which you clearly aren't using. :rolleyes: Prior to C++11 it's not as simple, but still doable:

vector<string> v;
long result = 0;


for (vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
    string x = *it;

    reverse(x.begin(), x.end());

    stringstream ss(x);
    long temp;

    ss >> temp;
    result += temp;

long long was added in C++11, so now you really need to be careful not to overflow long or use a big number library to avoid overflow.

Edited by deceptikon


This is really what I really need to do to my inputs.

Read long integers as strings and store the digits of the number in the vector in reverse order.


Read long integers as strings and store the digits of the number in the vector in reverse order.

Then straight C++ won't be enough. The 32-bit limit on long and even 64-bit limit on long long may not be sufficient to store the final value. You need something like GMP or Boost.Multiprecision to extend that limit indefinitely.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.