C++ cout with prefix

后端 未结 4 1680
醉话见心
醉话见心 2021-01-07 14:15

I want a ostream with a prefix at the beginning of every line redirected on cout; I try this:

#include 
#include 
class paralle         


        
4条回答
  •  日久生厌
    2021-01-07 15:09

    As Dietmar said, what you want is your own streambuf, something on this general order:

    #include 
    #include 
    
    class prefixer: public std::streambuf {
    public:
        prefixer(std::streambuf* s): sbuf(s) {}
        ~prefixer() { overflow('\n'); }
    private:
        typedef std::basic_string string;
    
        int_type overflow(int_type c) {
    
            if (traits_type::eq_int_type(traits_type::eof(), c))
                return traits_type::not_eof(c);
            switch (c) {
            case '\n':
            case '\r':  {
                prefix = "[FIX]";
                buffer += c;
                if (buffer.size() > 1)
                    sbuf->sputn(prefix.c_str(), prefix.size());
                int_type rc = sbuf->sputn(buffer.c_str(), buffer.size());
                buffer.clear();
                return rc;
            }
            default:
                buffer += c;
                return c;
            }
        }
    
        std::string prefix;
        std::streambuf* sbuf;
        string buffer;
    };
    

    To use this, you create an instance of it from some other streambuf (that defines where it's going to write to) and then (usually) create an ostream using this streambuf. Then you can write to that ostream, and your prefix gets written to each line of output. For example:

    int main() { 
        prefixer buf(std::cout.rdbuf());
    
        std::ostream out(&buf);
    
        out << "Test\n";
    }
    

提交回复
热议问题