Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

c++ - How to convert std:string to CString in unicode project

I have a std::string. I need to convert this std:string to a Cstring.

I try to use the .c_str() but it's only for non-unicode project and i use unicode project ( because non unicode project are depreceated wiht VS2013).

Anyone could show my how to convert an std::string to a CString in unicode project ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CString has a conversion constructor taking a const char* (CStringT::CStringT). Converting a std::string to a CString is as simple as:

std::string stdstr("foo");
CString cstr(stdstr.c_str());

This works for both UNICODE and MBCS projects. If your std::string contains embedded NUL characters you have to use a conversion constructor with a length argument:

std::string stdstr("foo");
stdstr += '';
stdstr += "bar";
CString cstr(stdstr.c_str(), stdstr.length());

Note that the conversion constructors implicitly use the ANSI code page of the current thread (CP_THREAD_ACP) to convert between ANSI and UTF-16 encoding. If you cannot (or do not want to) change the thread's ANSI code page, but still need to specify an explicit code page to use for the conversion, you have to use another solution (e.g. the ATL and MFC String Conversion Macros).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...