Problem: How to convert CString into const char *

2019-02-27 13:35发布

问题:

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.

回答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);


回答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).


回答3:

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().)



回答4:

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.



回答5:

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;
}