redirect std::cout to a custom writer

前端 未结 5 1192
生来不讨喜
生来不讨喜 2020-12-08 18:14

I want to use this snippet from Mr-Edd\'s iostreams article to print std::clog somewhere.

#include 
#include 
#include 

        
5条回答
  •  既然无缘
    2020-12-08 18:17

    I think you want to pull the text from the ostream while it's not empty. You could do something like this:

    std::string s = oss.str();
    if(!s.empty()) {
        // output s here
        oss.str(""); // set oss to contain the empty string
    }
    

    Let me know if this isn't what you wanted.

    Of course, the better solution is to remove the middle man and have a new streambuf go wherever you really want it, no need to probe later. something like this (note, this does it for every char, but there is plenty of buffering options in streambufs as well):

    class outbuf : public std::streambuf {
    public:
        outbuf() {
            // no buffering, overflow on every char
            setp(0, 0);
        }
    
        virtual int_type overflow(int_type c = traits_type::eof()) {
            // add the char to wherever you want it, for example:
            // DebugConsole.setText(DebugControl.text() + c);
            return c;
        }
    };
    
    int main() {
        // set std::cout to use my custom streambuf
        outbuf ob;
        std::streambuf *sb = std::cout.rdbuf(&ob);
    
        // do some work here
    
        // make sure to restore the original so we don't get a crash on close!
        std::cout.rdbuf(sb);
        return 0;
    

    }

提交回复
热议问题