I come from C background, while learning C++ I came across the <string> header file. In C strings would be an array of characters terminated by '\0'.
However, in std::string I found that this is not the case, and on inserting/replacing a null character at any valid index does not trim the string as I would have expected.
string s; getline(cin, s); // remove all punctuation for(string::size_type i = 0, n = s.size(); i < n; i++) { if(ispunct(s[i])) s[i] = '\0'; } input: Hello, World!!!!
output: Hello World
expected output: Hello
On observing the above behaviour I assumed that strings in C++ are not null terminated. Then I found this question on SO Use of null character in strings (C++) This got me confused.
string s = "Hello\0, World"; cout << s << endl; output: Hello
expected output: Hello, World
It would be helpful if anyone could explain the reason behind this behaviour.
std::stringlike astd::vector<char>that has a hidden extra element which is '\0'. That is an implementation detail though. The only guaranteed way to get a null-terminated array is throughstd::string::c_str().std::stringfrom the<string>header. Strings of this second kind are not null terminated arrays of characters.