Constructing a std::string with Embedded Null
When attempting to create a std::string with an embedded null character using syntax like std::string my_string("a\0b");, only one character is retained. This occurs because the std::string constructor expects a C-string, which is null-terminated. Upon encountering the null character, parsing halts.
To construct a std::string with an embedded null correctly, consider the following approaches:
C 14 and Later:
Introduce string literals using the s suffix to create a std::string without interpreting the null characters. This can be achieved with:
std::string s = "pl-<pre class="brush:php;toolbar:false">std::string x("pqrs", 5);
Before C 14:
Utilize a string constructor that accepts a character array and its length:
Remember that std::string doesn't utilize null-termination. However, via the c_str() method, you can obtain a pointer to an internal buffer containing a C-string.
The above is the detailed content of How Can I Create a std::string with an Embedded Null Character?. For more information, please follow other related articles on the PHP Chinese website!