vs2010 使用Unicode字符集 CString 与 char *相互转换

来源:互联网 发布:aaa云主机怎么绑定域名 编辑:程序博客网 时间:2024/05/21 22:29

CString转换为char *          

        CString strCheckIP ;
GetDlgItemText(IDC_IPADDRESS,strCheckIP);       

方法一:使用API:WideCharToMultiByte进行转换  

        //注意:以下n和len的值大小不同,n是按字符计算的,len是按字节计算的

int n = strIP.GetLength();                                           

        //获取宽字节字符的大小,大小是按字节计算的                  

int len = WideCharToMultiByte(CP_ACP,0,strIP,strIP.GetLength(),NULL,0,NULL,NULL);        

        //多字节字符数组申请空间,数组大小为按字节计算的宽字节字节大小

        char * pIP = new char[len+1];           //以字节为单位,

           //宽字节编码转换成多字节编码

WideCharToMultiByte(CP_ACP,0,strCheckIP,strCheckIP.GetLength(),pIP,len,NULL,NULL);      
pIP[len] ='\0';                                   //多字节字符以'\0'结束


方法二:使用函数:T2A、W2A   

       USES_CONVERSION;                                        //声明标识符
       char * pIP1 =T2A(strCheckIP);                              //调用函数,T2A和W2A均支持ATL和MFC中的字符转换
       addrTo.sin_addr.s_addr = inet_addr(pIP1);        //设置地址
       char * pIP2 = W2A(strCheckIP);                            //也可实现转换
       注意:有时候可能还需要添加引用#include  <afxpriv.h>


char *转换为CString    

        char szHostName[MAX_PATH + 1];

gethostname(szHostName, MAX_PATH);      //得到计算机名
hostent *p = gethostbyname(szHostName);    //从计算机名得到主机信息
if(p == NULL)
{
AfxMessageBox(L"得到本机网络信息失败!");
return NULL;
}

       char *pIP = inet_ntoa(*(in_addr *)p->h_addr_list[0]);               //将32位IP转化为字符串IP

方法一:使用_T() ,将字符串转换为宽字符     
CString str =_T("测试字符串转换");

方法二:使用API:MultiByteToWideChar进行转换   
CString m_strName;
//m_strName.Format(L"%s",szHostName);        //保存主机名 
        int charLen = strlen(szHostName);                      //计算char *数组大小,以字节为单位,一个汉字占两个字节    
        int len =MultiByteToWideChar(CP_ACP,0,szHostName,charLen,NULL,0);   //计算多字节字符的大小,按字符计算。     
       TCHAR *buf = new TCHAR[len + 1];                    //为宽字节字符数组申请空间,数组大小为按字节计算的多字节字符大小     
       MultiByteToWideChar(CP_ACP,0,szHostName,charLen,buf,len);          //多字节编码转换成宽字节编码
       buf[len] ='\0';                                                            //添加字符串结尾,注意不是len+1      
       m_strName.Append(buf);

方法三:使用函数:A2T、A2W   
CString m_strAddr;
//m_strAddr.Format(L"%s",pIP);                        //保存主机IP地址
USES_CONVERSION;
        m_strAddr = A2T(pIP);


LPARAM 转 CString     

        LPARAM lParam
//LPARAM->CString 方法一
CString str1((char*)lParam);


//LPARAM->CString 方法二
CString str2;
        str2 = (char*)lParam; // --运算符重载


//LPARAM->CString 方法三  vs2010 乱码 
CString str3;
str3.Format(L"%s", (char*)lParam);


0 0
原创粉丝点击