【发布时间】:2011-07-26 11:13:15
【问题描述】:
如何将 CString 转换为 const char *?我已经尝试了在互联网上找到的所有内容,但我仍然无法转换它们。
请帮忙。
谢谢。
【问题讨论】:
标签: c++ visual-c++ mfc
如何将 CString 转换为 const char *?我已经尝试了在互联网上找到的所有内容,但我仍然无法转换它们。
请帮忙。
谢谢。
【问题讨论】:
标签: c++ visual-c++ mfc
首先:定义 char *inputString;在 your_file.h 中
第二:在 yourFile.cpp 中定义: CString 我的字符串;
MyString = "Place here whatever you want";
inputString = new char[MyString.GetLength()];
inputString = MyString.GetBuffer(MyString.GetLength());
最后两句将 CString 变量转换为 char*;但要小心,使用 CString 您可以保存数百万个字符,但使用 char* 没有。您必须定义 char* 变量的大小。
【讨论】:
CString 直接转换为 const char *
CString temp;
temp = "Wow";
const char * foo = (LPCSTR) temp;
printf("%s", foo);
将打印'foo'
较新版本的 MFC 也支持 GetString() 方法:
CString temp;
temp = "Wow";
const char * foo = temp.GetString();
printf("%s", foo);
【讨论】:
我知道已经晚了,但我无法使用标记为答案的解决方案。我在整个互联网上搜索,没有任何东西对我有用。我努力解决问题:
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;
}
【讨论】:
简答:使用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()等函数。)
【讨论】: