Skip to content

Instantly share code, notes, and snippets.

@loloof64
Created October 31, 2017 18:22
Show Gist options
  • Save loloof64/2d2a845efda66154b89910cf976abb27 to your computer and use it in GitHub Desktop.
Save loloof64/2d2a845efda66154b89910cf976abb27 to your computer and use it in GitHub Desktop.
Simple stream redirection and listener try
#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