Home > Article > Backend Development > How Can I Embed Null Characters in a C std::string?
If you desire to create a std::string containing an embedded null character, you must tackle various syntax nuances depending on the C version you employ.
C 14 introduced string literals, providing a convenient method for constructing std::strings with embedded nulls:
#include <iostream> #include <string> using namespace std::string_literals; int main() { std::string s = "pl-<pre class="brush:php;toolbar:false">std::string x("pqrs"); // Two characters, as input is interpreted as a C-string std::string x("pqrs", 5); // 5 Characters, as input is now a char array with 5 characters-op"s; // Notice the "s" at the end, indicating a std::string literal std::cout << s << "\n"; }
Before C 14, the std::string constructor expecting a const char* assumed C-strings, which are null-terminated. To overcome this, you must use the constructor that takes a char array and a length:
<🎝🎝🎝>The above is the detailed content of How Can I Embed Null Characters in a C std::string?. For more information, please follow other related articles on the PHP Chinese website!