宽窄字符串Hanford2016年09月13日目录第1章宽窄字符串 6第1章宽窄字符串VC++中的字符串有两种,如下所示:constchar* pA = "窄字符串,即ANSI字符串";constwchar_t* pW = L"宽字符串,即Unicode字符串";本文将对这两种字符串的相互转换进行说明。,最终都要调用两个API函数:MultiByteToWideChar、WideCharToMultiByte。下面的三段代码演示了如何使用这两个函数:{//Ansi==>Unicodeconstchar* pA = "字符串";int nLenU = MultiByteToWideChar(CP_ACP,0,pA,-1,NULL,0);wchar_t* pW = (wchar_t*)malloc(nLenU*sizeof(wchar_t));MultiByteToWideChar(CP_ACP,0,pA,-1,pW,nLenU);MessageBoxW(GetActiveWindow(),pW,L"Ansi==>Unicode",MB_OK);free(pW);}{//Unicode==>Ansiconstwchar_t* pW = L"字符串";int nLenA = WideCharToMultiByte(CP_ACP,0,pW,-1,NULL,0,NULL,NULL);char* pA = (char*)malloc(nLenA);WideCharToMultiByte(CP_ACP,0,pW,-1,pA,nLenA,NULL,NULL);MessageBoxA(GetActiveWindow(),pA,"Unicode==>Ansi",MB_OK);free(pA);}{//UTF8==>Unicodeconstchar* pUTF8 = "\xE5\xAD\x97\xE7\xAC\xA6\xE4\xB8\xB2";int nLenU = MultiByteToWideChar(CP_UTF8,0,pUTF8,-1,NULL,0);wchar_t* pW = (wchar_t*)malloc(nLenU*sizeof(wchar_t));MultiByteToWideChar(CP_UTF8,0,pUTF8,-1,pW,nLenU);MessageBoxW(GetActiveWindow(),pW,L"UTF8==>Unicode",MB_OK);free(pW);}说明:1、转换时MultiByteToWideChar、WideCharToMultiByte均调用了两次。第一次用来获取转换后的字符数,根据此数值分配内存。第二次完成编码转换;2、CP_ACP、CP_UTF8说明了窄字符串的代码页。其中CP_ACP表示系统默认的ANSI字符串代码页。对于简体中文操作系统而言,CP_ACP表示代码页936即GBK;3、对于非简体中文操作系统,上述代码要想正常工作需要做如下改进:1)判断系统是否已经安装了代码页936,可使用函数GetCPInfoEx;2)将CP_AC
VC++宽窄字符串-16.09.13 来自淘豆网m.daumloan.com转载请标明出处.