Problem: How to convert CString into const char * in C++ MFC

25,159

Solution 1

CString casts to const char * directly

CString temp;
temp = "Wow";
const char * foo = (LPCSTR) temp;
printf("%s", foo);

will print 'foo'

Newer version of MFC also support the GetString() method:

CString temp;
temp = "Wow";
const char * foo = temp.GetString();
printf("%s", foo);

Solution 2

Short answer: Use the CT2CA macro (see ATL and MFC String Conversion Macros). This will work regardless of your project's 'Character Set' setting.

Long answer:

  • If you have the UNICODE preprocessor symbol defined (i.e., if TCHAR is wchar_t), use the CT2CA or CW2CA macro.
  • If you don't (i.e., if TCHAR is char), CString already has an operator to convert to char const* implicitly (see CSimpleStringT::operator PCXSTR).
Share:
25,159
Chicko Bueno
Author by

Chicko Bueno

Updated on April 27, 2020

Comments

  • Chicko Bueno
    Chicko Bueno about 4 years

    How do I convert CString into const char *? I have tried everything found on the internet but I still cant convert them.

    Please help.

    Thank you.

  • user2568374
    user2568374 over 4 years
    error C2440: 'type cast': cannot convert from 'ATL::CString' to 'LPCSTR'