Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector of char to stringstream

is it possible to convert char vector to std::stringstream? For example:

std::vector<unsigned char> data;
std::stringstream st(????);

Is there any way by which I can assign value of data to st?

like image 603
Rahul_cs12 Avatar asked Feb 10 '15 11:02

Rahul_cs12


3 Answers

If we look at the std::stringstream constructors, we see that the second one is:

explicit basic_stringstream( const std::basic_string<CharT,Traits,Allocator>& str,
                ios_base::openmode mode = ios_base::in|ios_base::out );

And the constructors of basic_string include:

template< class InputIt >
basic_string( InputIt first, InputIt last, 
              const Allocator& alloc = Allocator() );

Thus, we can do:

std::vector<unsigned char> data(20);

std::stringstream st(std::string(data.begin(), data.end()));
like image 119
Barry Avatar answered Oct 17 '22 09:10

Barry


Provided vec vector and strstr (o)stringstream:

copy(vec.begin(), vec.end(), ostream_iterator<char>(strstr));
like image 1
Ethouris Avatar answered Oct 17 '22 07:10

Ethouris


If you try to do:

std::stringstream st(data.data());

You will get this error from gcc:

error: invalid user-defined conversion from 'unsigned char*' to 'const __string_type& {aka const std::basic_string&}' [-fpermissive]

Note that gcc is trying to convert the argument into a std::string.

Barry suggests explicitly constructing the std::string in his answer.

But if your std::vector<unsigned char> data is null terminated then you can leverage the implicit construction. You'll just need to change to something that a std::string can be constructed from.

std::stringstream st(reinterpret_cast<char*>(data.data()));

A potentially easier solution would be to change the type of std::vector<unsigned char> data to std::vector<char> data. In which case no cast is required:

std::stringstream st(data.data());
like image 1
Jonathan Mee Avatar answered Oct 17 '22 09:10

Jonathan Mee