Not sure if this is the problem.
Adding '\0' in the middle of std::string does not change anything - the null character is treated like any other. The only thing that can change is to use .c_str() with a function that accepts null-terminated strings. But then this is not a .c_str() problem, only with a function that processes '\0' specifically.
If you want to know how many characters this string has, as if it were being treated as a string with a null character, use
size_t len = strlen(s.c_str());
Note that this is an O (n) operation, since strlen works.
If you ask why the += operator does not add the invisible null character of the string literal "hello" to the string, I say that the reverse (adding) is unclear and definitely not what you want 99% of the time, On the other hand, if you want to add '\0' in your line, just add it as a buffer:
char buffer[] = "Hello"; s.append(buffer, sizeof(buffer));
or (even better) completely discard char arrays and null-terminated strings and use C ++ type replacements such as std::string , like NTS replacement, std::vector<char> as a continuous buffer, std::vector as dynamic array with replacement pointers and std::array (C ++ 11) as a standard replacement for array C.
Also (as @AdamRosenfield mentioned in the comments), your line after adding "hello" really has 20 characters, probably only that your terminal does not print zeros.
source share