c++ - copying from a std::string to a char array and null-terminating the result -
i have visual studio 2008 c++03 application want copy std::string char array, need char array null terminated if must truncate string so.
this, instance works desired:
inline void copyandnullterminate( const std::string& source, char* dest, size_t dest_size ) { source.copy( dest, dest_size ); using std::min; char* end = dest + min( dest_size - 1, source.size() ); *end = '\0'; } int main() { enum{ max_string_size = 15 }; char dest[ max_string_size ]; std::string test = "this test"; copyandnullterminate( test, dest, max_string_size ); assert( strcmp( test.c_str(), dest ) == 0 ); return 0; }
example: http://ideone.com/0ebyb
is there shorter, more efficient method of doing this?
thanks
yes, use strncpy
, defined in cstring
:
void copystring(const std::string& input, char *dst, size_t dst_size) { strncpy(dst, input.c_str(), dst_size - 1); dst[dst_size - 1] = '\0'; }
note implementations of std::string
(as pointed out @k-ballo), may shorter, less efficient. due fact std::string
not guaranteed implemented using c-syle strings, although situations case.
Comments
Post a Comment