Last active
June 21, 2018 06:06
-
-
Save rudolfovich/9fc5bdd110d543b46afdbdd845a82377 to your computer and use it in GitHub Desktop.
Redirect std::cout and std::cin to string stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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