首页 > 代码库 > c++ wchar_t 与char 直接的转换【转】

c++ wchar_t 与char 直接的转换【转】

http://blog.163.com/tianshi_17th/blog/static/4856418920085209414977/

实现了一下

#include "stdafx.h"
#include <iostream>
#include <sstream>

using namespace std;

char* wchar2char(wchar_t *WStr)
{
	size_t len = wcslen(WStr) + 1;
	size_t converted = 0;
	char *CStr;
	CStr=(char*)malloc(len*sizeof(char));
	wcstombs_s(&converted, CStr, len, WStr, _TRUNCATE);
	return CStr;
}

wchar_t *char2wchar(char *CStr)
{
	size_t len = strlen(CStr) + 1;
	size_t converted = 0;
	wchar_t *WStr;
	WStr=(wchar_t*)malloc(len*sizeof(wchar_t));
	mbstowcs_s(&converted, WStr, len, CStr, _TRUNCATE);
	return WStr;
}

wstring char2wchar2(char *name)
{
	wstringstream wname;
	wname<<name;
	return wname.str().c_str();
}

int _tmain(int argc, _TCHAR* argv[])
{

	char name[]="zhangsan中国";
	wstring c2w2name = char2wchar2(name);
	wcout<<c2w2name.c_str()<<" wstring"<<endl;

	wchar_t *c2wname = char2wchar(name);
	wcout<<c2wname<<" c2w"<<endl;
	
	char *w2cname = wchar2char(c2wname);

	cout<<w2cname<<" w2c"<<endl;
	free (w2cname);
	free(c2wname);
	return 0;
}

  

c++ wchar_t 与char 直接的转换【转】