I have a Visual Studio 2008 C++03 application where I want to copy from a std::string to a char array, but I need the char array to be null terminated even if it must truncate the string to do so.
This, for instance works as 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 is a test";
CopyAndNullTerminate( test, dest, MAX_STRING_SIZE );
assert( strcmp( test.c_str(), dest ) == 0 );
return 0;
}
example: http://ideone.com/0EBYb
Is there a shorter, more efficient method of doing this?
Thanks
Yes, use
strncpy, defined incstring:Note that for some implementations of
std::string(as pointed out by @K-ballo), this may be shorter, but less efficient. This is due to the fact thatstd::stringis NOT guaranteed to be implemented using C-syle strings, although for most situations that is probably the case.