开发者

converting c style string to c++ style string

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜