刚学MFC,要用VC6读一个文件显示在编制辑框架内,是UTF-8格式,写了下列的转换代码,但前面多了个问号,不知何解?
字的字符:“DAC123456 ABC BC”;
代码:
CString CodeConvert(CString instr,int sourceCodepage,int targetCodepage) ////////////////////////
{
int len=instr.GetLength();
int unicodeLen=MultiByteToWideChar(sourceCodepage,NULL,instr,len,NULL,0);
wchar_t* unicodestring=new wchar_t[unicodeLen+1]; MultiByteToWideChar(sourceCodepage,NULL,instr,len,unicodestring,unicodeLen);
//BYTE * pTargetData;
int ansilen=WideCharToMultiByte(targetCodepage,NULL,unicodestring,unicodeLen,NULL,0,NULL,NULL);
char* ansidata=new char[ansilen+1]; WideCharToMultiByte(targetCodepage,NULL,unicodestring,unicodeLen,ansidata,ansilen,NULL,NULL); //转换
// ansidata[ansilen]="\0"; CString rt;
rt.Format("%s",ansidata); delete unicodestring;
delete ansidata;
return rt; }
调用 m_edit1=Convert(m_edit1,CP_UTF8,CP_ACP);
字的字符:“DAC123456 ABC BC”;
代码:
CString CodeConvert(CString instr,int sourceCodepage,int targetCodepage) ////////////////////////
{
int len=instr.GetLength();
int unicodeLen=MultiByteToWideChar(sourceCodepage,NULL,instr,len,NULL,0);
wchar_t* unicodestring=new wchar_t[unicodeLen+1]; MultiByteToWideChar(sourceCodepage,NULL,instr,len,unicodestring,unicodeLen);
//BYTE * pTargetData;
int ansilen=WideCharToMultiByte(targetCodepage,NULL,unicodestring,unicodeLen,NULL,0,NULL,NULL);
char* ansidata=new char[ansilen+1]; WideCharToMultiByte(targetCodepage,NULL,unicodestring,unicodeLen,ansidata,ansilen,NULL,NULL); //转换
// ansidata[ansilen]="\0"; CString rt;
rt.Format("%s",ansidata); delete unicodestring;
delete ansidata;
return rt; }
调用 m_edit1=Convert(m_edit1,CP_UTF8,CP_ACP);
MultiByteToWideChar(CP_UTF8, ...);
WideCharToMultiByte(CP_ACP, ...);
你把instr前三个字符去掉应该就行了。
{
CString result;
WCHAR *strSrc = NULL;
TCHAR *szRes = NULL;
char *str = strData.GetBuffer(strData.GetLength());
strData.ReleaseBuffer();
int i;
// UTF8转换成Unicode
i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i+1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
// Unicode转换成GB2312
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new TCHAR[i+1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
if (strSrc != NULL)
{
delete []strSrc;
strSrc = NULL;
}
if (szRes != NULL)
{
delete []szRes;
szRes = NULL;
}
return result;
}
这个函数我一直在用,你试试看