Is a null-terminated string returned from getline ()?

One thing I'm not sure about after I searched a lot of time is the getline () return string. Hope this is confirmed here.

std::getline 

This global version returns std :: string , so it does not necessarily end with zero. Some compilers may add '\ 0', while others may not.

 std::istream::getline 

This function returns a c-style string, so it is guaranteed that the string is terminated with a null character.

Is it correct?

+4
source share
2 answers

Null end is a concept that applies only to C strings; it does not apply to std::string objects - they allow you to find the size by calling size() , and do not require zero completion. However, the strings returned from the std::string c_str() function have zero completion, regardless of where the data for the std::string c_str() from.

The C ++ 11 standard describes the operator [pos] prerequisites in section 21.4.5.2:

Returns: *(begin() + pos) if pos < size() . Otherwise, a reference is returned to an object of type charT with the value charT() , where changing the object leads to undefined behavior.

Pay attention to pos < size() , not pos <= size() : the standard explicitly allows std::string objects to have zero completion.

+4
source

The trailing null character, which signals the end of line c, is automatically added to s after data extraction.

0
source

Source: https://habr.com/ru/post/1447847/


All Articles