Skip to content

Instantly share code, notes, and snippets.

@rudolfovich
Last active June 21, 2018 06:06
Show Gist options
  • Save rudolfovich/9fc5bdd110d543b46afdbdd845a82377 to your computer and use it in GitHub Desktop.
Save rudolfovich/9fc5bdd110d543b46afdbdd845a82377 to your computer and use it in GitHub Desktop.
Redirect std::cout and std::cin to string stream
#include <iostream>
#include <sstream>
class StdIOStreamRedirect
{
std::streambuf *cinbuf_;
std::streambuf *coutbuf_;
std::istringstream in_;
std::ostringstream out_;
public:
StdIOStreamRedirect()
: cinbuf_(std::cin.rdbuf())
, coutbuf_(std::cout.rdbuf())
{
std::cin.rdbuf(in_.rdbuf());
std::cout.rdbuf(out_.rdbuf());
}
~StdIOStreamRedirect()
{
std::cin.rdbuf(cinbuf_); //reset to standard input again
std::cout.rdbuf(coutbuf_); //reset to standard output again
}
std::string output() { return out_.str(); }
//template<class T>
//std::istream & operator >> (const T & value) { return in_ >> value; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment