How to use record in stringstream?

I have a vector<char> data that I want to write to std::stringstream .

I tried:

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

... but it doesn't seem to put anything in my_ss , which I set out as follows:

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

Why does the record not work (the application does not crash and compiles with 0 errors, 0 warnings)?

+4
source share
3 answers

For "how to do this," you can use std::ostream_iterator :

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

Full 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 can also just use this to directly build a string without going through stringstream at all:

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

Although you haven't provided any code yet, it looks like you probably just wrote:

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

If you want to write a string stream, you need to combine the std::stringstream::out flag in the constructor. If I am right, then you will see that everything is working fine, if you changed this to:

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

(Obviously, if you want to read from this string stream, you need to add std::stringstream::in )

UPDATE Now that you have your code ... yup, this is your specific problem. Please note that @awoodland indicates that you can simply build a string from a character vector instead (if this is the only thing you planned to do with this thread.)

+4
source

The default parameter for stringbuf mode in stringstream is disabled | 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

+3
source

Source: https://habr.com/ru/post/1381713/


All Articles