Summary
Encountered problem in convert from string to CString (LPCWSTR), and the reverse convert, find out the way to convert between these two types and tested in Visual Studio with successful result.
The unicode setting is configured in the Visual Studio project property page –> Configuration Properties –> General –> Character Set –> Use Unicode Character Set, as below picture shows,
Different string types description as below, as How to convert std::string to LPCSTR? mentioned,
LPSTR
- (long) pointer to string - char *
LPCSTR
- (long) pointer to constant string - const char *
LPWSTR
- (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR
- (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR
- (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR
- (long) pointer to constant TCHAR string - const TCHAR *
C++ convert from string to LPCWSTR
As you know, std::string
is char*
type, while LPCWSTR
,LPWSTR
or CString
is wchar_t*
as long as the Visual Studio configured as Unicode Character Set.
I am using How to convert std::string to LPCSTR? solution as below code solved this problem,
Refer to the How to convert string to LPCTSTR? solution 5, it is the similar solution as above by using MultiByteToWideChar
function,
C++ convert from LPCWSTR to string
To convert from LPCWSTR
to string
, can split into two steps, first step convert fromCString
to wchar_t
, 2nd step, convert from wchar_t
to char*
, as below code shows,
Below code from MSDN is working perfectly for the conversion from wchar_t*
to char*
by using wcstombs_s
function,
Reference
1, MSDN, Converts a sequence of wide characters to a corresponding sequence of multibyte characters
2, How to convert string to LPCTSTR?
3, How to convert std::string to LPCSTR?