wchar* 转到 char*
方法一,使用_bstr_t转换。
#include <comdef.h> // youwill need this
constWCHAR* wc = L"Hello World" ;
_bstr_t b(wc);
constchar* c = b;
printf("Output:%s\n",c);
方法二,使用conversion macros。
包含在头文件#include<atlconv.h>
中,使用需谨慎!因为转换字符串分配的空间在栈上,直到函数返回才释放。如归使用很多次,例如在递归函数里使用,容易造成内存溢出。
USES_CONVERSION;
WCHAR* wc = L"Hello World" ;
char*c = W2A(wc);
方法三,使用sprintf,比较简洁。
char output[256];
WCHAR* wc = L"Hellow World" ;
sprintf(output, "%ws", wc );
char*转 wchar*
方法一:使用mbstowcs函数。
constwchar_t *GetWC(constchar *c)
{
const size_t cSize = strlen(c)+1;
wchar_t* wc = newwchar_t[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
方法二:使用USES_CONVERSION。
用法及注意事项同上。
USES_CONVERSION;
char* c = L"Hello World" ;
Wchar* wc = A2W(c);
方法三:使用swprintf函数,推荐使用。
wchar_t ws[100];
swprintf(ws, 100,L"%hs", "ansistring");
例子:
#include<iostream>
#include <comdef.h>
using namespace std;
int main()
{
const WCHAR* wc = L"徐炜杰" ;
_bstr_tb(wc);
constchar* c=b;
cout<<c;
return 0;
}