Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returned string null-terminated from getline()?

One thing I'm not pretty sure after googling for a while, is the returned string of getline(). Hope to get it confirmed here.

std::getline

This global version returns a std::string so it's not necessarily null-terminated. Some compilers may append a '\0' while the others won't.

std::istream::getline

This function returns a c-style string so it's guaranteed that the string is null-terminated.

Is that right?

like image 931
Eric Z Avatar asked Nov 23 '12 01:11

Eric Z


1 Answers

Null termination is a concept that is applicable only to C strings; it does not apply to objects of std::string - they let you find the size by calling size(), and do not require null termination. However, strings returned from std::string's c_str() function are null terminated, regardless of where the data for the string came from.

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

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

Note the pos < size(), as opposed to pos <= size(): the standard explicitly allows std::string objects not to have null termination.

like image 96
Sergey Kalinichenko Avatar answered Nov 20 '22 03:11

Sergey Kalinichenko