wchar_t转char wchar_t*转char*

wchar_t转char

第一种方法

string   tp; 
wchar_t   *s; 
char   *d; 
tp=s; 
d=tp.c_str(); 

第二种方法:自定义函数实现

#include <windows.h>
#include <stdio.h>

void charTowchar(const char *chr, wchar_t *wchar, int size)
{   
	MultiByteToWideChar( CP_ACP, 0, chr,
        strlen(chr)+1, wchar, size/sizeof(wchar[0]) );
}

void wcharTochar(const wchar_t *wchar, char *chr, int length)
{
    WideCharToMultiByte( CP_ACP, 0, wchar, -1,
        chr, length, NULL, NULL );
}

int main (void)
{
	char     chr[128];
	wchar_t  *wchar = L"你猜";
	

	//wchar_t to char
	wcharTochar(wchar, chr, sizeof(chr));
	printf("char is %s\n", chr);

	//char to wchar_t
	wchar = (wchar_t *)malloc(sizeof(wchar_t) * 64);
	charTowchar(chr, wchar, sizeof(wchar_t) * 64);
	
	wprintf_s(L"%s\n", wchar);
	getchar();
	return 0;
}


wchar_t*转char*

第一种方法

wchar_t *wch=_T("你猜你猜"); 
int size=WideCharToMultiByte(CP_ACP,0,wch,-1,NULL,0,NULL,NULL); 
char *ch=new char[size+1]; 
if(!WideCharToMultiByte(CP_ACP,0,wch,-1,ch,size,NULL,NULL)) 

    return false; 
}

wchar_t* wstr = L"A wide character string.";

char* ascii = new char[wcslen(wstr) + 1];

wcstombs( ascii, wstr, wcslen(wstr) );


第二种方法

 size_t size;  

 int requiredSize;  

 requiredSize = wcstombs( NULL, pwchello, 0);

pmbhello = (unsigned char *)malloc( requiredSize + 1);  

size = wcstombs( pmbhello, pwchello, requiredSize + 1);

char* 转换为 wchar_t*     

 size_t size; 

 int requiredSize;    

requiredSize = mbstowcs(NULL, pmbhello, 0);  

pwc = (wchar_t *)malloc( (requiredSize + 1) * sizeof( wchar_t ));  

size = mbstowcs( pwc, pmbhello, requiredSize + 1);



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值