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

后端 未结 5 670
囚心锁ツ
囚心锁ツ 2021-01-21 11:32

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.

相关标签:
5条回答
  • 2021-01-21 11:42

    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;
    }
    
    0 讨论(0)
  • 2021-01-21 11:46

    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.

    0 讨论(0)
  • 2021-01-21 11:48

    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);
    
    0 讨论(0)
  • 2021-01-21 11:53

    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).
    0 讨论(0)
  • 2021-01-21 11:55

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

    0 讨论(0)
提交回复
热议问题