2011-03-30 98 views

回答

7

的CString蒙上爲const char *直接

CString temp; 
temp = "Wow"; 
const char * foo = (LPCSTR) temp; 
printf("%s", foo); 

將打印 '富' MFC的

較新的版本還支持getString()方法:

CString temp; 
temp = "Wow"; 
const char * foo = temp.GetString(); 
printf("%s", foo); 
3

簡短回答:使用宏CT2CA(請參閱ATL and MFC String Conversion Macros)。無論項目的「字符集」設置如何,這都可以工作。

龍答:

  • 如果你有UNICODE預處理符號定義(即,如果TCHARwchar_t),使用CT2CACW2CA宏。
  • 如果你不知道(即如果TCHARchar),CString已經有一個隱式轉換爲char const*的操作符(見CSimpleStringT::operator PCXSTR)。
0

如果您的應用程序不是Unicode,您可以簡單地轉換爲const char *。如果您需要可修改的char *,請使用GetBuffer()方法。

如果您的應用程序是Unicode,並且您確實需要char *,那麼您需要將其轉換。 (你可以使用功能,如MultiByteToWideChar()

-1

我知道這是晚了,但我不能使用標記爲答案的解決方案。我在互聯網上搜索,沒有爲我工作。我通過它肌肉得到一個解決方案:

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

第一:define char * inputString; in your_file.h

第二:在你的File.cpp中定義: CString MyString;

MyString = "Place here whatever you want"; 

inputString = new char[MyString.GetLength()]; 
inputString = MyString.GetBuffer(MyString.GetLength()); 

最後兩個句子將CString變量轉換爲char *;但要小心,用CString你可以容納多個charcteres但char * no。你必須定義char * varible的大小。