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., ifTCHAR
iswchar_t
), use theCT2CA
orCW2CA
macro. - If you don't (i.e., if
TCHAR
ischar
), CString already has an operator to convert tochar const*
implicitly (seeCSimpleStringT::operator PCXSTR
).
Author by
Chicko Bueno
Updated on April 27, 2020Comments
-
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 over 4 yearserror C2440: 'type cast': cannot convert from 'ATL::CString' to 'LPCSTR'