For regular C strings, a null character '\0' signifies the end of data.
What about std::string, can I have a string with embedded null characters?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes you can have embedded nulls in your
std::string.Example:
Note:
std::string‘sc_str()member will always append a null character to the returned char buffer; However,std::string‘sdata()member may or may not append a null character to the returned char buffer.Be careful of operator+=
One thing to look out for is to not use
operator+=with achar*on the RHS. It will only add up until the null character.For example:
The correct way:
Storing binary data more common to use std::vector
Generally it’s more common to use
std::vectorto store arbitrary binary data.It is probably more common since
std::string‘sdata()andc_str()members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.