Search code examples
c++capturecout

Capture/redirect cout to a function


Is it possible to capture cout in a way so that every standard output (cout << "example";) automatically calls a function (myfunc("example");)?


Solution

  • One way would be to create a class which had the appropriate operator<< overloads and create a global instance called cout and to using std::whatever instead of using namespace std;. It would then be easy enough to switch back and forth from your custom cout to std::cout.

    That's just one solution though (which may require a decent amount of work, more than you want to spend), I'm sure other people know better ways.