basic6
basic6

Reputation: 3811

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");)?

Upvotes: 2

Views: 1624

Answers (2)

Paul Hutchinson
Paul Hutchinson

Reputation: 1728

What you need to do is make a new class inherited from std::streambuf and overload the virtual function virtual int overflow(int c);. You then need to use rdbuf() on cout to this class.

After you connect it up to cout the overflow() will be called with every character output.

Example:

#include <iostream>
#include <stdio.h>

class MyCOutClass: public std::streambuf
{
private:
    virtual int overflow(int c)
    {
        if (c == EOF)
        {
            return !EOF;
        }
        else
        {
            if(c=='\n')
                printf("\r");
            printf("%c",c);

            return c;
        }
    }
};

class MyCOutClass MyCOut;

int main(void)
{
    std::cout.rdbuf(&MyCOut);

    std::cout << "testing" << std::endl;

    return 0;
}

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75150

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.

Upvotes: 2

Related Questions