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

相关文章:

  • 2021-09-10
  • 2021-12-06
  • 2021-10-12
  • 2021-09-25
  • 2022-12-23
猜你喜欢
  • 2021-06-16
  • 2022-12-23
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
相关资源
相似解决方案