Does std :: string c_str () always return a null-terminated string?
Yes.
This is the specification:
Returns: a pointer p such that p + i == &operator[](i) for each i in [0,size()] .
Note that the range specified for i is closed, so size() is a valid index, referring to the character that has passed after the end of the line.
operator[] specified like this:
Returns: *(begin() + pos) if pos < size() , otherwise a reference to an object of type T with value charT()
In the case of std::string , which is an alias for std::basic_string<char> , so that charT is char , the constructed char value has a value of 0; therefore, the character array pointed to by the result of std::string::c_str() ends with zero.
Mike seymour
source share