Question: I was solving the following problem:
*Reverse the digits of an integer.* Now the code for the problem is straightforward. 

```
void reverse(int x){
   if(x < 0){
      cout << "-";
      x*=(-1);
   }

   while(x!=0){
      cout << x%10;
      x/=10;
   }
}

```

But the problem asked the answer to be returned as integer. So I was wondering is there any way the output stream can be redirected to an integer. I know I could redirect it to a string and then convert to integer. But is there any direct way?

Answer: 
You can use an `std::ostringstream`, save `std::cout` buffer, and then convert it to int:

```
void reverse(int x)
{
    std::ostringstream local_buffer;
    auto old_buff = std::cout.rdbuf(local_buffer.rdbuf()); // save pointer to std::cout buffer

    if(x < 0){
        std::cout << "-";
        x*=(-1);
    }

    while(x!=0){
        std::cout << x%10;
        x/=10;
    }

    std::cout.rdbuf(old_buff); // back to old buffer

    int rev = std::atoi(local_buffer.str().c_str());

    std::cout << "rev is: " << rev << "\n";
}

```

[Online on Coliru](http://coliru.stacked-crooked.com/a/ece28dc3736b2bfd)
Why not creating a function that returns int?

```
#include <cmath> // needed for pow()

int reverse(int x)
{    
  int y=0;
  int numDigits=0;
  int x2=x;

  // first count number of digits

  while(x2!=0){
  x2/=10;
  numDigits++;
  }

  // then do the reversion by adding up in reverse direction

  for(int i=0; i<numDigits; i++){
  y+=(x%10)*pow(10,numDigits-i-1);
  x/=10;
  }

  return y;
}

```