如何將CString轉換爲const char *?我已嘗試在互聯網上找到的所有東西,但我仍然不能轉換它們。問題:如何將CString轉換爲C++ MFC中的const char *
請幫忙。
謝謝。
如何將CString轉換爲const char *?我已嘗試在互聯網上找到的所有東西,但我仍然不能轉換它們。問題:如何將CString轉換爲C++ MFC中的const char *
請幫忙。
謝謝。
的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);
簡短回答:使用宏CT2CA
(請參閱ATL and MFC String Conversion Macros)。無論項目的「字符集」設置如何,這都可以工作。
龍答:
UNICODE
預處理符號定義(即,如果TCHAR
是wchar_t
),使用CT2CA
或CW2CA
宏。TCHAR
是char
),CString已經有一個隱式轉換爲char const*
的操作符(見CSimpleStringT::operator PCXSTR
)。如果您的應用程序不是Unicode,您可以簡單地轉換爲const char *
。如果您需要可修改的char *
,請使用GetBuffer()
方法。
如果您的應用程序是Unicode,並且您確實需要char *
,那麼您需要將其轉換。 (你可以使用功能,如MultiByteToWideChar()
)
我知道這是晚了,但我不能使用標記爲答案的解決方案。我在互聯網上搜索,沒有爲我工作。我通過它肌肉得到一個解決方案:
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;
}
第一: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的大小。
[轉換CString爲const char *]的可能重複(http://stackoverflow.com/questions/859304/convert-cstring-to-const-char) – ChrisN 2011-03-31 10:01:32