Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::string have a null terminator?

Tags:

c++

string

null

Will the below string contain the null terminator '\0'?

std::string temp = "hello whats up"; 
like image 238
mister Avatar asked Aug 01 '12 04:08

mister


People also ask

Do strings in C++ end with null character?

In C the strings are basically array of characters. In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0').

Can std::string be null?

Thus, NULL isn't a valid value for a std::string. They *can't* really be NULL. The relevant overloads for std::string are to compare a std::string to a std::string, a char* to a std::string, or a std::string to a char*.


1 Answers

No, but if you say temp.c_str() a null terminator will be included in the return from this method.

It's also worth saying that you can include a null character in a string just like any other character.

string s("hello"); cout << s.size() << ' '; s[1] = '\0'; cout << s.size() << '\n'; 

prints

5 5

and not 5 1 as you might expect if null characters had a special meaning for strings.

like image 139
jahhaj Avatar answered Oct 02 '22 01:10

jahhaj