How to initialise a stringstream from a vector char
Asked Answered
L

2

5

currently I am using a boost char array

boost::array<char, 512> received_data;
std::istringstream ss_(received_data.data()); 

but what if my received_data was a std::vector<char> received_data(512);

how would I then get this data to my std::istringstream ss_?

Lotze answered 25/5, 2013 at 14:39 Comment(2)
There is no easy (and correct) way to do this properly. To do it right you either have to use boost or implement your own streambuf (which isn't too hard).Beefwood
Possible duplicate of C++: Wrapping vector<char> with istreamBeefwood
O
6

The istringstream takes a string, and a string can be made from two char iterators, like this:

istringstream iss(string(v.begin(), v.end()));
Osmium answered 25/5, 2013 at 14:43 Comment(1)
This makes an unnecessary copy of the data.Beefwood
S
2
std::vector<char> receivedData(512);

std::istringstream iss(&receivedData[0]);
Scrimpy answered 25/5, 2013 at 14:41 Comment(3)
Good if there's no 0s in the data and the last is a 0.Krick
@user494461, The iterator pair.Krick
If there is a 0 in the middle of the std::vector<char> then the iterator version will only take the part up to the 0 too as far as I can tell, with that said the iterator version is preferred.Explicate

© 2022 - 2024 — McMap. All rights reserved.