How do I use write with stringstream?

2019-05-03 20:32发布

问题:

I have a vector<char> of data which I want to write into std::stringstream.

I tried:

my_ss.write(vector.data(), vector.size());

...but it seems to put nothing into my_ss which I declared as follows:

std::stringstream my_ss( std::stringstream::binary);

Why write is not working (app does not crash and compiles with 0 errors, 0 warnings)?

回答1:

For the "how do I do it" you can use a std::ostream_iterator:

std::copy(vector.begin(), vector.end(), std::ostream_iterator<char>(my_ss));

Complete example:

#include <iterator>
#include <sstream>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
  std::vector<char> vector(60, 'a');
  std::ostringstream my_ss;
  std::copy(vector.begin(), vector.end(), std::ostream_iterator<char>(my_ss));
  std::cout << my_ss.str() << std::endl;
}

You could also just use that to construct a string directly, without going via a stringstream at all:

std::string str(vector.begin(), vector.end()); // skip all of the copy and stringstream


回答2:

Though you haven't given any code, it sounds like you probably just wrote:

std::stringstream my_ss (std::stringstream::binary);

If you wish to write to a stringstream you need to combine the flag std::stringstream::out in the constructor. If I'm right, then you would see things working fine if you changed this to:

std::stringstream my_ss (std::stringstream::out | std::stringstream::binary);

(Obviously if you wish to read from that stringstream you need to add std::stringstream::in)

UPDATE Now that you've given your code...yup, this is your specific problem. Note @awoodland's point about the fact that you can just construct a string from a vector of chars instead (if that's the only thing you were planning on doing with this stream.)



回答3:

The default parameter for the mode of stringbuf in stringstream is out|in.

explicit basic_stringstream(ios_base::openmode _Mode =
    ios_base::in | ios_base::out)
    : _Mybase(&_Stringbuffer),
        _Stringbuffer(_Mode)
    {   // construct empty character buffer
    }

You need to add stringstream::out if you pass something explicitly like stringstream:binary

Or just use std::ostringstream