Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 438
Walter Fabio Simoni Avatar asked Oct 27 '13 10:10

Walter Fabio Simoni


People also ask

Is CString same as string?

The two headers are completely different. cstring is inherited from C and provides functions for working with C-style strings (arrays of char terminated by '\0' ). string was born in C++ and defines the std::string class along with its non-member functions. It compares the numeric values of the characters.

Does CString include string?

CString accepts NULL-terminated C-style strings. CString tracks the string length for faster performance, but it also retains the NULL character in the stored character data to support conversion to LPCWSTR .

What is string C_str ()?

The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.


2 Answers

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 += '\0';
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).

like image 59
IInspectable Avatar answered Oct 01 '22 19:10

IInspectable


Use the ATL conversion macros. They work in every case, when you use CString. CString is either MBCS or Unicode... depends on your Compiler Settingss.

std::string str = "string";
CString ss(CA2T(str.c_str());
like image 27
xMRi Avatar answered Oct 01 '22 18:10

xMRi