Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stringstream >> int returns zero

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

like image 549
jonnydark Avatar asked Dec 21 '22 21:12

jonnydark


1 Answers

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];
}
like image 179
Alessandro Pezzato Avatar answered Dec 24 '22 02:12

Alessandro Pezzato