In the below code I am trying to replace the first character with '\0'
.
I expected it to print an empty string, but in the output it just omits that and displays the rest of the characters.
int main() { string str; cin >> str; str[0] = '\0'; cout << str << "\n"; return 0; }
OUTPUT :
testing esting
How do I terminate the string in C++?
PS: I was trying this approach of terminating the string in a different question in which I need to terminate in between.
You can't have a null character in the middle of a C string, because a null character, by definition, ends the string. You can use arrays of chars where some of them are null characters, but you have to treat them as arrays, not strings.
All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.
Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be NULL.
\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).
std::string
is not a null terminated string. If you want to empty it use the clear()
method. If you want to remove an element of the string use the erase()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With