CString转char*

1.传给未分配内存的const char* (LPCTSTR)指针. 

CString cstr = "asdd";

const char* ch = (LPCTSTR)cstr;

ch指向的地址和cstr相同。但由于使用const保证ch不会修改,所以安全.

注意此种方法只能在non-UNICODE builds中使用。

2.传给未分配内存的指针.

CString cstr = "ASDDSD";

char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);

cstr.ReleaseBuffer();

修改ch指向的值等于修改cstr里面的值.

PS:用完ch后,不用delete ch,因为这样会破坏cstr内部空间,容易造成程序崩溃.

3.把CString 值赋给已分配内存的char *。

CString cstr1 = "ASDDSD";

int strLength = cstr1.GetLength() + 1;

char *pValue = new char[strLength];

strncpy(pValue, cstr1, strLength);

4.把CString 值赋给已分配内存char[]数组.

CString cstr2 = "ASDDSD";

int strLength1 = cstr1.GetLength() + 1;

char chArray[100];

memset(chArray,0, sizeof(bool) * 100); //将数组的垃圾内容清空.

strncpy(chArray, cstr1, strLength1);
5、使用CT2A宏
为了把一个TCHAR CString转换成ASCII字符串,可以用CT2A宏——它允许你把字符串转换成UTF8(或者任何其他Windows code page),如:
// Convert using the local code pageCString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);

// Convert to UTF8CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);

// Convert to Thai code pageCString str(_T("Some Thai text"));
CT2A ascii(str,874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);

还有一个从ASCII到Unicode转换的宏(CA2T),只要你有2003或更高版本的VS,你就可以在ATL/WTL应用程序中使用这些宏。

See the MSDN for more info.

ref:

http://www.lewensky.cn/read.php/133.htm

http://forums.codeguru.com/showthread.php?231153-MFC-String-How-to-convert-a-CString-to-a-char*

http://stackoverflow.com/questions/859304/convert-cstring-to-const-char

原文地址:https://www.cnblogs.com/cloud2rain/p/3015596.html