xtran888
asked on
Convert CString to char*
How to convert CString to char *
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>>> 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
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
>>> 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
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.