wchar_t 和 char 之间转换

vc++2005以后,Visual studio 编译器默认的字符集为Unicode。VC中很多字符处理默认为宽字符wchar_t,如CString的getBuffer(),而一些具体操作函数的输入却仍要求是单字符的char,这边需要对两者进行转换。查阅网上若干多资料,总结为一下几种方法。

方法一:WideCharToMultiByte()和 MultiByteToWideChar()

 1.1 wchar_t   转为  char

 使用函数 WideCharToMultiByte(),此函数把宽字符串转换成指定的新的字符串,如ANSI 等,新字符串不必是多字节字符集。

wchar_t* pwszUnicode = L"Holle";  //wcslen(pwsUnicode)=5
int iSize; char* pszMultiByte;

//返回接受字符串所需缓冲区的大小,已经包含字符结尾符'' iSize
= WideCharToMultiByte(CP_ACP, 0, pwszUnicode, -1, NULL, 0, NULL, NULL); //iSize =wcslen(pwsUnicode)+1=6
pszMultiByte = (char*)malloc(iSize*sizeof(char)); //不需要 pszMultiByte = (char*)malloc(iSize*sizeof(char)+1);
WideCharToMultiByte(CP_ACP, 0, pwszUnicode, -1, pszMultiByte, iSize, NULL, NULL);

1.2 char  转为  wchar_t

  使用函数 MultiByteToWideChar(),此函数把多字节字符串转换成宽字符串(Unicode),待转换的字符串并不一定是多字节的。

char* pszMultiByte = "Holle";  //strlen(pwsUnicode)=5
int iSize; 
wchar_t
* pwszUnicode ;

//返回接受字符串所需缓冲区的大小,已经包含字符结尾符''
iSize = MultiByteToWideChar(CP_ACP, 0, pszMultiByte , -1, NULL, 0); //iSize =wcslen(pwsUnicode)+1=6
pwszUnicode = (wchar_t *)malloc(iSize*sizeof(wchar_t)); //不需要 pwszUnicode = (wchar_t *)malloc((iSize+1)*sizeof(wchar_t))
MultiByteToWideChar(CP_ACP, 0, pszMultiByte , -1, pwszUnicode , iSize);

参考:

http://www.cnblogs.com/wind-net/archive/2012/10/31/2718329.html

http://www.cnblogs.com/tclikang/archive/2012/06/11/2544771.html

http://blog.csdn.net/fengshalangzi/article/details/5815073

方法二: stdlib.h中的mbstowcs_s() 和 wcstombs_s()

2.1 wchar_t 转为  char

stdlib.h中的wcstombs_s函数,例子:

#include <stdlib.h>


wchar_t *WStr = L"string to convert"; 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);

这时WStr中的内容将被转化为char版本储存在CStr中。

2.2 char*转换为wchar_t*

stdlib.h中的mbstowcs_s函数,例子:


#include <stdlib.h>

char
*CStr = "string to convert"; 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);

其结果是WStr中储存了CStrwchar_t版本。

 

方法三:

外还可以通过流的方法来char*类型转换为wchar_t*类型,但这样的转换得到的结果将是const类型,而类似的方法不能将wchar_t*类型转换为char*类型。

constchar*  转换为 const wchar_t*

需要用到 sstream 头文件:

#include<sstream>

char *cstr="string to convert";

wstringstream wss;

wss<<cstr;

 

再调用wss.str().c_str(); 即可得到 const wchar_t* 类型的返回值。

虽然stringstream流不能将wchar_t*转换成char*,但可以用来进行数值类型和字符串之间的转换,例如:

double d=2734792.934f;

stringstream ss;

ss<<d;

调用ss.str()可得到string类型字符串 ”273479e+006”,又如:

string str("299792458");

stringstream ss;

long i=0;

ss<<str;

ss>>i;

 

此时i=299792458

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

原文地址:https://www.cnblogs.com/vranger/p/3792791.html