VC++ 多字节宽字符相互转换

多字节宽字符相互转换用的较多,自己写了一点留作以后参考。

 

 

string str;
 
 cout<<"please input chinese"<<endl;
 cin>>str;
 //setlocale(LC_CTYPE,".chs");
 const char* cstr1 = str.c_str();
 //int len = 2*sizeof(cstr);
 
 int WLen = MultiByteToWideChar(CP_ACP,             // code page
                                   0,                // character-type options
           cstr1,              // string to map
                                   -1,                 // number of bytes in string
                                   NULL,            // wide-character buffer
                                   0                // size of buffer
);
    wchar_t * buffer = new wchar_t[WLen+1];
 int RetWLen = MultiByteToWideChar(CP_ACP,             // code page
                                   0,                // character-type options
           cstr1,              // string to map
                                   -1,                 // number of bytes in string
                                   buffer,            // wide-character buffer
                                   WLen                // size of buffer
);
 buffer[WLen] = '/0';
printf("/nthe translated num is %d",RetWLen);

-----------------------------------------------------

------------------------------------------------------

---------------------------------------------------------

--------------------------------------------------------

同理 宽字符到多字节
 int MLen = WideCharToMultiByte(
                                   CP_ACP,            // code page
                                   0,            // performance and mapping flags
                                   buffer,    // wide-character string
                                   -1,          // number of chars in string
                                   NULL,     // buffer for new string
                                   0,          // size of buffer
                                   NULL,     // default for unmappable chars
                                   NULL  // set when default char used
); //这里第六个参数若为0 表示 返回 宽字符对应多字节的长度
 char* MultiBte = new char[MLen+1]; 
 int RetMLen = WideCharToMultiByte(
                                   CP_ACP,            // code page
                                   0,            // performance and mapping flags
                                   buffer,    // wide-character string
                                   -1,          // number of chars in string
                                   MultiBte,     // buffer for new string
                                   MLen,          // size of buffer
                                   NULL,     // default for unmappable chars
                                   NULL  // set when default char used
); //完成转换
printf("/nthe translated MultiByte num is :%d",RetMLen);
printf("/nthe Multibyte value:");
MultiBte[MLen]='/x0';
fputs(MultiBte,stdout); //可直接在终端输出

 头文件 windows.h

 

你可能感兴趣的:(String,null,buffer,input,vc++,performance)