Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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?

like image 363
Gemma Morriss Avatar asked Dec 03 '22 21:12

Gemma Morriss


1 Answers

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.

like image 153
user4815162342 Avatar answered Dec 21 '22 13:12

user4815162342