Paul Morriss Paul Morriss - 1 month ago 6
C++ Question

std::vector<char> to std::string

I am trying to convert a

std::vector<char>
into a string using:

// Data has been received, update the buffer...
buffer = readBuffer.data();
buffer[bytesRead-1] = '\0';


The issue I am having is that when I debug readBuffer I get
"<A HREF="https://www.google.com/">here</A>."


but on reviewing buffer I get
'<A HREF="https://ww ²²²²▌▌╫$Ö►¬∟☺.google.com/">here</A>.'


Is there something really obvious I missing?

Answer

Writing a null character at the end of a character vector will not magically create an std::string. To create an actual std::string, use something like:

std::string s = std::string(readBuffer.begin(), readBuffer.end());

You don't need to explicitly append the null character to the string, the std::string constructor will do it for you.