您的位置:首页 > 其它

char/wchar_t之间的互转MultiByteToWideChar和WideCharToMultiByte的用法

2011-05-06 21:25 399 查看
C2W char->wchar_t

W2C wchar_t->char

注意 codpage参数选择CP_OEMCP这样中文和英文都可以成功转换,如果只要转换英文可以使用CP_ACP

bool C2W(const char* str,wchar_t* wstr)
{
int len=MultiByteToWideChar(CP_OEMCP,0,str,-1/*null terminated*/,wstr,0);
return len==MultiByteToWideChar(CP_OEMCP,0,str,-1/*null terminated*/,wstr,len);
}
bool W2C(const wchar_t* wstr,char* str)
{
int len=WideCharToMultiByte(CP_OEMCP,0,wstr,-1/*null terminated*/,str,0,0,0);
return len==WideCharToMultiByte(CP_OEMCP,0,wstr,-1/*null terminated*/,str,len,0,0);
}


  

用例:这里要注意使用setlocale(LC_CTYPE,"chs");,使得wprintf(wstr);能正确打印汉字。

#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(LC_CTYPE,"chs");
wchar_t wstr[256];
C2W("abc汉字/n",wstr);
wprintf(wstr);
char str[256];
W2C(L"abc汉字/n",str);
printf(str);
return 0;
}


也可以使用wcstombs和mbstowcs两个函数:

http://blog.csdn.net/iamoyjj/archive/2011/06/29/6575798.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: