Using << operator to write to both a file and cout

前端 未结 6 1113
滥情空心
滥情空心 2020-12-02 01:10

I\'d like to overload << operator to write the value it takes to a file and cout. I have tried to do it with following code, but couldn\'t succeed it. It just writes t

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 01:23

    If you are able to use it, you will find that, not unsurprisingly, the boost library has already done most of the hard work for you.

    #include 
    #include 
    #include 
    #include 
    
    typedef boost::iostreams::tee_device teedev;
    typedef boost::iostreams::stream, std::allocator< typename std::ostream::char_type > > tee_stream;
    
    int main(int argc, char* argv[])
    {
        std::ofstream of;
        of.open( "test.txt" );
    
        teedev td( of, std::cout );
        tee_stream ts(td);
    
        ts << "!!!Hello World!!!" << std::endl;
    
        return 0;
    }
    

提交回复
热议问题