Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUL char in strings in C++

Tags:

c++

string

c++11

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.

like image 674
user3351750 Avatar asked Jun 27 '14 13:06

user3351750


People also ask

How do you give a null character to a string?

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.

Does string have null character?

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.

Can you set a string to null in C?

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.

What is the use of '\ 0 character?

\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 ).


1 Answers

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.

like image 65
Marius Bancila Avatar answered Oct 13 '22 01:10

Marius Bancila