Search code examples
c++type-conversionstdstringstream

converting stringstream to stl containers


I want to convert some stringstream to vector, but I lost all my spaces during it.

class Wrapper {
public:
    vector<char> data;
    Wrapper(std::stringstream &s) {
        std::cout << s.str();  //output: 22 serialization::archive 16 0 0 2
        for (char c; s >> c;)
            data.push_back(c);

        std::cout << '\n';
        for (auto i = data.begin(); i != data.end(); ++i)
            std::cout << *i; // output: 22serialization::archive1600222
    }
};

...

new Wrapper(stream);

Also my conversation method don't looks elegant. Is there are better way to do it?


Solution

  • As noted in the comments by Some programmer dude, operator>> skips spaces by default.

    It is possible to directly construct a std::vector<char> from a std::stringstream using the appropriate overload and a couple of std::istreambuf_iterators:

    #include <iostream>
    #include <vector>
    #include <sstream>
    #include <iterator>
    
    int main(void)
    {
        std::stringstream ss;
        ss << 22 << " serialization::archive " << 16 << ' ' << 0 << ' ' << 0 << ' ' << 2;
    
        std::vector<char> data {
            std::istreambuf_iterator<char>(ss),
            std::istreambuf_iterator<char>(),   // <- default-constructed end of stream iterator
        };
    
        // it outputs: 22 serialization::archive 16 0 0 2
        for (auto i = data.begin(); i != data.end(); ++i)
            std::cout << *i;
    }