Created
October 31, 2017 18:22
-
-
Save loloof64/2d2a845efda66154b89910cf976abb27 to your computer and use it in GitHub Desktop.
Simple stream redirection and listener try
This file contains hidden or 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> | |
#include <streambuf> | |
#include <string> | |
class OStringStreamListener | |
{ | |
public: | |
virtual void consume(const std::string &input) = 0; | |
}; | |
class OStringStreamWithEmitter : public std::ostringstream | |
{ | |
public: | |
OStringStreamWithEmitter(OStringStreamListener &listener) : _listener(listener){}; | |
std::ostream &operator<<(const std::string &input); | |
private: | |
OStringStreamListener &_listener; | |
}; | |
std::ostream &OStringStreamWithEmitter::operator<<(const std::string &input) | |
{ | |
_listener.consume(input); | |
std::ostringstream << input << std::endl; | |
return *this; | |
} | |
class SampleOStringStreamListener : public OStringStreamListener | |
{ | |
public: | |
SampleOStringStreamListener(){}; | |
~SampleOStringStreamListener(){}; | |
std::streambuf *rdbuf() const | |
{ | |
return rdbuf(); | |
} | |
std::string getAll() const; | |
void consume(const std::string &input); | |
private: | |
std::string _customBuffer; | |
}; | |
void SampleOStringStreamListener::consume(const std::string &input) | |
{ | |
_customBuffer += input; | |
} | |
std::string SampleOStringStreamListener::getAll() const | |
{ | |
return _customBuffer; | |
} | |
int main() | |
{ | |
using namespace std; | |
SampleOStringStreamListener stringStreamListener; | |
OStringStreamWithEmitter coutRedirected(stringStreamListener); | |
streambuf *coutBackup = cout.rdbuf(coutRedirected.rdbuf()); | |
cout << "Hello !" << endl; | |
cout << "How are you ?" << endl; | |
cout.rdbuf(coutBackup); | |
cout << "------Got----------" << endl; | |
cout << stringStreamListener.getAll() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment