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)
You can convert it to a string and go backwards and send it to a stringstream.

```
std::stringstream s;

std::string s = std::to_string(x);
for (std::string::reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit) {
    std::cout << *rit;
    ss << *rit;
}
std::cout << std::endl;
return stoi(ss.str());

```

Add

```
#include <sstream>

```

I ran the int- and string-version 2.5 mill. times in a loop and the string-version is twice as fast on my macbook pro 2012. 1.2 secs. vs 2.4 secs. Something to consider using strings even though it may be seldom used.

Update:

Another SO [answer](https://stackoverflow.com/questions/24372480/reverse-string-c-using-char-array) suggests std::reverse and when I updated the code to

```
auto s = std::to_string(x);
std::reverse(s.begin(), s.end());
return stoi(s);

```

it used 0.8 secs., three times faster than swapping digits.