CString转char*字符串

在做windows平台的即时通讯小程序时,要从编辑框获得输入的字符串,在用socket函数发送给另一端。项目属性是UNICODE的。

从编辑框获得字符串是CString,而socket函数需要的是char字符串。发现转换有点麻烦,CString本身没提供这个功能啊。


纠结后总结的解决方案如下:

非UNICODE工程:

1.获得CString存储字符串的内存地址,在强制转换或直接复制出来。

例:

CString strTemp;
char szTemp[128];

strTemp = _T("abckdkfei");
memset( szTemp, 0, sizeof(szTemp) );
strcpy( szTemp, strTemp.GetBuffer(0) );


2.用(LPSTR)(LPCSTR)强制转换

例:

char *buf; 

CString str = "hello"; 
buf = (LPSTR)(LPCTSTR)str;

上面两种方法的原理都是基于CString类把char字符串保存了。得到其内部字符串首地址就可以把数据复制出来,或直接强制转换。


UNICODE工程

UNICODE工程有上面的方法会报错的。应为WCAHR不能直接转换成char,所以可在上面的基础上用WideCharToMultiByte函数转换一下。

例:

CString sendString;
m_sendEdit.GetWindowText(sendString);
m_sendEdit.SetWindowText(L"");


char buf[1024] = {'\0'};
WideCharToMultiByte(CP_ACP,0,sendString.GetBuffer(0),sendString.GetLength(),buf,1024,0,0);
send(clientSocket,buf,strlen(buf),0);


3.用CString类的成员函数:OemToANSI()即可。这个方法我没验证。查了一下MSDN的解释:

 

 

CString::OemToAnsi


Visual Studio 6.0此主题尚未评级 -
CString::OemToAnsi


void OemToAnsi( );
Remarks
Converts all the characters in this CString object from the OEM character set to the ANSI character set. See the http://technet.microsoft.com/zh-cn/library/ms857349.aspx in the C++ Language Reference.
This function is not available if _UNICODE is defined.


原文地址:https://www.cnblogs.com/javawebsoa/p/2992135.html