C++/cstrings and strings in c++
Expert: vijayan - 8/15/2008
Question
hello, Vijayan
i want to convert from cstring to strings and vice versa
how can i do this?
thanks
Answerc strings are simply arrays of char terminated by a null char.
eg. char cstr[] = "hello" ;
cstr is an array of chars [ 'h', 'e', 'l', 'l', 'o', '\0' ]
a std::string is a class which implements a resizable sequence of chars.
converting from a c string to a std::string is easy, std::string has a (non-explicit)
constructor which takes a const char* and c strings (arrays) decay into pointers.
all this would work:
char cstr[] = "hello" ;
std::string str = cstr ;
str = "bye for now" ;
char cstr2[128] ;
str = std::strcpy( cstr2, "hello world" ) ;
note: strcpy returns a char*
to convert from a std::string to a c string, use the member function c_str() ;
it returns a non-modifiable c string which is null terminated.
eg.
std::string str = "hello world" ;
const char* cstr = str.c_str() ;
char dest[256] ;
assert( str.size() < sizeof(dest) ) ;
std::strcpy( dest, str.c_str() ) ;
note: the pointer returned by c_str() is invalid after modifications to the std::string.