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
i
starts from 0, then initial.size() - i
is out of string bounds.
Change to ss << initial[initial.size() - i - 1];
and iterate i
from 1 to initiali.size() - 1
for(unsigned i = 0; i != initial.size(); ++i) {
ss << initial[initial.size() - i -1];
}
Or iterate i
from 1 to initial.size()
for(unsigned i = 1; i <= initial.size(); ++i) {
ss << initial[initial.size() - i];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With