initializing a C++ std::istringstream from an in memory buffer?

前端 未结 4 939
时光取名叫无心
时光取名叫无心 2020-11-30 06:22

I have a memory block (opaque), that I want to store in a Blob in mySQL through their C++ adapter. The adapter expects a istream:

virtual void setBlob(unsign         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 06:48

    It's actually pretty trivial to write a one-shot std::streambuf that uses the buffer in place as the default behaviour of all the virtual functions of std::streambuf does 'the right thing'. You can just setg the read area in construction and underflow and uflow can safely be left to return traits_type::eof() as the end of the initial get area is the end of the stream.

    e.g.:

    #include 
    #include 
    #include 
    #include 
    
    struct OneShotReadBuf : public std::streambuf
    {
        OneShotReadBuf(char* s, std::size_t n)
        {
            setg(s, s, s + n);
        }
    };
    
    char hw[] = "Hello, World!\n";
    
    int main()
    {
        // In this case disregard the null terminator
        OneShotReadBuf osrb(hw, sizeof hw - 1);
        std::istream istr(&osrb);
    
        istr >> std::cout.rdbuf();
    }
    

提交回复
热议问题