You are constructing your std::string from a string literal. String literals are automatically terminated with a '\0'. A string literal "f\0o" is thus encoded as the following array of characters:
{'f', '\0', 'o', '\0'}
The string constructor taking a char const* will be called, and will be implemented something like this:
string(char const* s) { auto e = s; while (*e != '\0') ++e; m_length = e - s; m_data = new char[m_length + 1]; memcpy(m_data, s, m_length + 1); }
Obviously this isn't a technically correct implementation, but you get the idea. The '\0' you manually inserted will be interpreted as the end of the string literal.
If you want to ignore the extra '\0', you can use a std::string literal:
#include <iostream> #include <string> int main () { using namespace std::string_literals; std::string s("String!\0 This is a string too!"s); std::cout << s.length(); // same result as with s.size() std::cout << std::endl << s; return 0; }
Output:
30 String! This is a string too!