This is actually trickier than it looks, because you can't call strlen
unless the string is actually nul terminated. In fact, without some
additional constraints, the problem practically requires inventing a new
function, a version of strlen
which never goes beyond the a certain
length. However:
If the buffer containing the c-style string is guaranteed to be at least
max_length
char's (although perhaps with a '\0'
before the end),
then you can use the address-length constructor of std::string
, and
trim afterwards:
std::string result( c_string, max_length );
result.erase( std::find( result.begin(), result.end(), '\0' ), result.end() );
and if you know that c_string
is a nul terminated string (but perhaps
longer than max_length
, you can use strlen
:
std::string result( c_string, std::min( strlen( c_string ), max_length ) );