converting c style string to c++ style string

Viewed 41857

Can anyone please tell me how to convert a C style string (i.e a char* ) to a c++ style string (i.e. std::string) in a C++ program?

Thanks a lot.

4 Answers

std::string can take a char * as a constructor parameter, and via a number of operators.

char * mystr = "asdf";
std::string mycppstr(mystr);

or for the language lawyers

const char * mystr = "asdf";
std::string mycppstr(mystr);
char* cstr = //... some allocated C string

std::string str(cstr);

The contents of cstr will be copied to str.

This can be used in operations too like:

std::string concat = somestr + std::string(cstr);

Where somestr is already `std::string``

You can make use of the string class constructor which takes a char* as argument.

char *str = "some c style string";
string obj(str);

Another way to do the conversion is to call a function which takes a const std::string& as a parameter:

void foo(const std::string& str);

void bar()
{
    char* str= ...

    foo(str);
}

I think its a lot more tidy to do the conversion at a function call boundary.

Related