多字节字符类型 | 宽字节字符类型 |
---|---|
char |
wchar_t |
使用WideCharToMultiByte
MultiByteToWideChar
int wchar2char(char* &str,const wchar_t* wstr)
{
int len= WideCharToMultiByte( CP_ACP ,0,wstr ,wcslen( wstr ), NULL,0, NULL ,NULL );
str= new char[len+1];
WideCharToMultiByte( CP_ACP ,0,wstr ,wcslen( wstr ),str,len, NULL ,NULL );
str[len]= '\0';
return len;
}
int char2wchar(wchar_t* &wstr,const char* str)
{
int len = MultiByteToWideChar(CP_UTF8,0,str,strlen(str), NULL,0);
wstr = new wchar_t[len+1];
MultiByteToWideChar( CP_UTF8 ,0,str,strlen(str),wstr,len);
wstr[len]= '\0';
return len;
}
使用:
wchar_t* text;
if(char2wchar(text,"鸡你太美") < 0){
cout<<"Failed to convert.";
}
//wcout<
MessageBoxW(NULL,text,L"Caption",MB_OK);
mbstowcs
wcstombs
int char2wchar(wchar_t* &wStr,const char* str){
//setlocale(LC_ALL,"zh_CN.UTF-8");
size_t w_len = mbstowcs(NULL, str, 0) + 1;
if (w_len == 0){
wStr = NULL;
return -1;
}
wStr=(wchar_t*)malloc(w_len*sizeof(wchar_t));
if (!wStr){
return -1;
}
mbstowcs(wStr, str, w_len);
return w_len;
}
//wchar to char func is similar。
调用也和上面一样,别忘了free
mbstowcs_s
wcstombs_s
char* wchar2char(const wchar_t* wStr){
char *str;
size_t len = wcslen(wStr) + 1;
size_t converted = 0;
str=(char*)malloc(len*sizeof(char));
wcstombs_s(&converted, str, len, wStr, _TRUNCATE);
char* res = str;
free(str);
return res;
}
PS:如果你文件是utf8的中文可能会有乱码,加上setlocale(LC_ALL,“zh_CN.UTF-8”);
Linux还有可能显示不出来,但我们一般都只在win上用WCHAR。