首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

wchar 与 char 的交换

2012-12-28 
wchar与 char 的互换#include iostream#include stdio.h#include windows.h using namespace std//

wchar 与 char 的互换

 #include <iostream>    #include <stdio.h>#include <windows.h> using namespace std;//#include <tchar.h>char *w2c(char *pcstr,const wchar_t *pwstr, size_t len);void c2w(wchar_t *pwstr,size_t len,const char *str);int main(int argc, char* argv[]){wchar_t pwstr[] =L"我是中国人";printf("===============");wprintf(L"原始数据 pwstr:%s",pwstr);wchar_t pwstr2[20];    char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(pwstr)+1));    memset(pcstr , 0 , 2 * wcslen(pwstr)+1 );    w2c(pcstr,pwstr,2 * wcslen(pwstr)+1) ;printf("wchar=>char result:%s\n",pcstr);   c2w(pwstr2,20,pcstr);   wprintf(L"%s",pwstr2);    free(pcstr) ;   return 0;}//将wchar_t* 转成char*的实现函数如下:char *w2c(char *pcstr,const wchar_t *pwstr, size_t len){int nlength=wcslen(pwstr);//获取转换后的长度int nbytes = WideCharToMultiByte( 0, // specify the code page used to perform the conversion0,         // no special flags to handle unmapped characterspwstr,     // wide character string to convertnlength,   // the number of wide characters in that stringNULL,      // no output buffer given, we just want to know how long it needs to be0,NULL,      // no replacement character givenNULL );    // we don't want to know if a character didn't make it through the translation// make sure the buffer is big enough for this, making it larger if necessaryif(nbytes>len)   nbytes=len;// 通过以上得到的结果,转换unicode 字符为ascii 字符WideCharToMultiByte( 0, // specify the code page used to perform the conversion0,         // no special flags to handle unmapped characterspwstr,   // wide character string to convertnlength,   // the number of wide characters in that stringpcstr, // put the output ascii characters at the end of the buffernbytes,                           // there is at least this much space thereNULL,      // no replacement character givenNULL );return pcstr ;}//将char* 转成wchar_t*的实现函数如下://这是把asii字符转换为unicode字符,和上面相同的原理void c2w(wchar_t *pwstr,size_t len,const char *str){if(str)    {      size_t nu = strlen(str);      size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)str,(int)nu,NULL,0);      if(n>=len)n=len-1;      MultiByteToWideChar(CP_ACP,0,(const char *)str,(int)nu,pwstr,(int)n);      pwstr[n]=0;    }}//或者用此种方法更好一些:============我自已做的//把ascii 字符转换为unicode字符//wchar_t* Cphone_hq::ctow(wchar_t *pwstr, const char *str)//{//wchar_t* buffer;//if(str)//    {//      size_t nu = strlen(str);//      size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),NULL,0);//      buffer=0;//      buffer = new wchar_t[n+1];//      //if(n>=len) n=len-1;//     ::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),buffer,int(n));    ////   }//return buffer;//delete buffer;//}

热点排行