I’m writing a function to return the reverse of a number i.e it converts int(1234) to int(4321). This is what I have currently:
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
int reverse(int num) {
stringstream ss (stringstream::in | stringstream::out);
string initial;
int reversed;
// read the number in to a string stream
ss << num;
initial = ss.str();
// flush the stringstream
ss.str("");
for(unsigned int i(0); i <= initial.size(); i++) {
ss << initial[initial.size() - i];
}
ss >> reversed;
return reversed;
}
int main(int argc, const char *argv[])
{
int test = 9871;
cout << "test = " << test << endl;
cout << "reverse = " << reverse(test) << endl;
return 0;
}
However this just outputs:
test = 9871
reverse = 0
And I’m pretty certain the problem is in the line ss >> reversed is the problem in that reversed is being set to 0 instead of the value of ss, but I can’t figure out what’s wrong with this code, and it’s infuriating as it seems like it should be simple. Can anyone help?
Thanks
istarts from 0, theninitial.size() - iis out of string bounds.Change to
ss << initial[initial.size() - i - 1];and iterateifrom 1 toinitiali.size() - 1Or iterate
ifrom 1 to initial.size()