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.