c++c++17stringstream

Is there a way to create a stringstream from a string_view without copying data?


I think that's a pretty straighforward question. I'd specifically like to use std::get_time, but it requires some sort of a stream to be used with. I am passing the data in a string_view and would like to avoid copying it just to parse the date.


Solution

  • You can do that easily with Boost.Iostreams library:

    #include <boost/iostreams/device/array.hpp>
    #include <boost/iostreams/stream.hpp>
    
    #include <iostream>
    #include <string>
    
    int main() {
        std::string_view buf{"hello\n"};
        boost::iostreams::stream<boost::iostreams::basic_array_source<char>> stream(buf.begin(), buf.size());
    
        std::string s;
        stream >> s;
        std::cout << s << '\n';
    }
    

    You should be able to do that with std::stringstream and std::basic_stringbuf<CharT,Traits,Allocator>::setbuf but the C++ standard botched its requirements:

    The effect [of setbuf] is implementation-defined: some implementations do nothing, while some implementations clear the std::string member currently used as the buffer and begin using the user-supplied character array of size n, whose first element is pointed to by s, as the buffer and the input/output character sequence.