Reputation: 863
I need to split a header and payload that I've read into a stringstream.
I've found the position of the start of the payload in the stringstream.
can read the header with:
// where ss is the source stringstream
ssHeader.read(ss.str(), nDataStartPos-1);
Now I'd like to read the remainder into a payload stringstream.
ssPayload.read(ss.str()+nDataStartPos, nTotalBytesRed);
This fails with the following errors:
error: invalid conversion from 'const char*' to 'char*'
initializing argument 1 of 'std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits]'
I'm guessing that the str() command returns a temporary, constructed from the internal buffers of the stringstream.
So I guess I could copy the ssPayload to a string, then do an substr, but is there a more efficient way to achieve this, or maybe stringstream is the wrong tool for the job?
Upvotes: 0
Views: 989
Reputation: 409166
If the data (header and payload) is text, then use plain std::string
and use substr
to extract the header and payload.
If the data is binary, then you might use std::vector<uint8_t>
(or std::vector<int8_t>
) and extract data using e.g. std::copy_n
. But if the data is binary, why not simple use packed structures that contain the exact data needed, including the header (possibly use two structures, one for the header and one for the payload)?
Upvotes: 1
Reputation: 385114
You guess correctly, and yes a stringstream is the wrong tool for the job.
Generally we read into a fixed buffer, repeatedly copying its contents into whatever you want until everything's been read.
And yes that kind of sucks.
You may be able to use stream iterators and std::copy
.
Upvotes: 2