Link to home
Start Free TrialLog in
Avatar of xtran888
xtran888

asked on

Convert CString to char*

How to convert CString to char *
ASKER CERTIFIED SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ichijo
Ichijo

If you only need read-only access to the string, you can cast the CString to LPCSTR, if your environment is setup for ANSI (multi-byte) strings.

CString sTest("test");
const char *p = (LPCSTR)sTest;

If your build environment is set for Unicode, you'll get a type cast error because then the CString will compile to Unicode, and so you would need to add code to convert the string at runtime.
>>>> const char *p = (LPCSTR)sTest;

CString has a built-in cast operator for LPCSTR (== const char*). So you need no cast:

    CString s = "Hello";
    const char* psz = s;  // no cast needed

That means wherever a const char* (LPCSTR) was used you may use a CString instead.

Regards, Alex


>>> If your build environment is set for Unicode, you'll get a
>>> type cast error because then the CString will compile to Unicode
Using the TCHAR and LPCTSTR will solve that either for UNICODE or non-UNICODE.

  CString s = _T("Hello");   // makes either LPCSTR or LPCWSTR on right side
  LPTSTR p = new TCHAR[20];   // left side is either char* or wchar_t*
                                                 // TCHAR is either char or wchar_t
  _tcscpy(p, s);   // here you don't need to cast to LPCTSTR as it is built-in
                          // _tcscopy makes strcpy in case of non-UNICODE and wcscpy for UNICODE