You are here:

C++/cstrings and strings in c++

Advertisement


Question

hello, Vijayan

i want to convert from cstring to strings and vice versa

how can i do this?

thanks

Answer
c 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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.