Problem: How to convert CString into const char *

2019-02-27 13:27发布

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条回答
倾城 Initia
2楼-- · 2019-02-27 13:47

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-27 13:51

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楼-- · 2019-02-27 13:52

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).
查看更多
何必那么认真
5楼-- · 2019-02-27 13:55

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;
}
查看更多
forever°为你锁心
6楼-- · 2019-02-27 13:57

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);
查看更多
登录 后发表回答