多字节编码和Unicode编码的转换。

经过测试可以使用 

 现变成两个函数:

CStringA UnicodeToAnsi(CStringW& wstr,int  Sel=0) 

CStringW AnsiToUnicode(char * pChar,int Sel)

再Unicode 编译环境下测试 MFC中测试使用。

 

CStringA UnicodeToAnsi(CStringW& wstr,int  Sel=0) 
{
	if(Sel==0)
	{
		int len=WideCharToMultiByte(CP_ACP,0,wstr.GetBuffer(0),-1,NULL,0,NULL,false);
		char *pstr = new char[len +1];
		memset(pstr,0,len+1);
		WideCharToMultiByte(CP_ACP,0,wstr.GetBuffer(0),-1,pstr,len+1,NULL,false);
		CStringA astr(pstr);
		delete[] pstr;
		return astr;
	}
	else if(1==Sel)
	{
		USES_CONVERSION;
		CStringA astr=T2A(wstr);
		return astr;
	}
	else if(2==Sel)
	{
		//不能转换中文
		int len=wstr.GetLength();
		char* pchar = (char* )malloc(len+1);
		memset(pchar,0,len+1);
		wcstombs(pchar,wstr.GetBuffer(0),len);
		CStringA as(pchar);
		free(pchar);
		return as;
	}
}
CStringW AnsiToUnicode(char * pChar,int Sel)
{
	if(Sel==0)
	{
		//int len =
		int len =MultiByteToWideChar(CP_ACP,0,pChar,-1,NULL,0);
		wchar_t *pwchar = new wchar_t[len+1];
		memset(pwchar,0,len+1);
		MultiByteToWideChar(CP_ACP,0,pChar,-1,pwchar,len);

		CStringW converstr(pwchar);
		delete[] pwchar;
		return converstr;
	}
	else if (1== Sel)
	{
		USES_CONVERSION;
		CStringW astr=A2T(pChar);
		return astr;
	}
	else if(2==Sel)
	{
		//不能转换中文
		int len =strlen(pChar);
		wchar_t* pwchar=(wchar_t* )malloc((len+1)*sizeof(wchar_t));
		memset(pwchar,0,(len+1)*sizeof(wchar_t));
		mbstowcs(pwchar,pChar,len);
		CStringW as1(pChar);
		CStringW as = pwchar;
                free(pwchar);
		return as;
	}
}

 

你可能感兴趣的:(c++)