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.
I know it's late, but I couldn't use the marked-as-answer solution. I search all over the internet and nothing worked for me. I muscled through it to get a solution:
char * convertToCharArr(CString str) {
int x = 0;
string s = "";
while (x < str.GetLength()) {
char c = str.GetAt(x++);
s += c;
}
char * output = (char *)calloc(str.GetLength() + 1, sizeof(char));
memcpy(output, s.c_str(), str.GetLength() + 1);
return output;
}
First : define char *inputString; in your_file.h
Second : define in yourFile.cpp : CString MyString;
MyString = "Place here whatever you want";
inputString = new char[MyString.GetLength()];
inputString = MyString.GetBuffer(MyString.GetLength());
The last two sentences convert a CString variable to a char*; but be carefull, with CString you can hold millons of charcteres but with char* no. You have to define the size of your char* varible.
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);
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:
UNICODE
preprocessor symbol defined (i.e., if TCHAR
is wchar_t
), use the CT2CA
or CW2CA
macro.TCHAR
is char
), CString already has an operator to convert to char const*
implicitly (see CSimpleStringT::operator PCXSTR).If your application is not Unicode, you can simple typecast to const char *
. Use the GetBuffer()
method if you need a char *
that you can modify.
If your application is Unicode and you really want a char *
, then you'll need to convert it. (You can use functions like MultiByteToWideChar()
.)