multi-byte wide-char

/*
 * C++ 字符串的一点点转换
 */
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <clocale> //setlocale
#include <Windows.h>
#include <WinCon.h>
using namespace std;
//using namespace System; //需要CLR支持


wchar_t* mbs2wcs(const char* mbstr)
{
wchar_t* wcstr = NULL;


// Get the size of wchar_t after converted
#ifdef WIN32
int size = MultiByteToWideChar(CP_UTF8, 0, mbstr, -1, NULL, 0);
#else
size_t size = mbstowcs(NULL, mbstr, 0);
#endif


wcstr = new wchar_t[size+1];
if (wcstr)
{
memset(wcstr, 0, size * sizeof(wchar_t));
#ifdef WIN32
int ret = MultiByteToWideChar(CP_UTF8, 0, mbstr, -1, wcstr, size);
if (ret == 0) // MultiByteToWideChar returns 0 if it does not succeed.
#else
size_t ret = mbstowcs(wcstr, mbstr, size+1);
if (ret == -1)
#endif
{
delete[] wcstr;
wcstr = NULL;
}
}


return wcstr;
}


char* wcs2mbs(const wchar_t* wcstr)
{
char* mbstr = NULL;


// Get the size of char after converted
#ifdef WIN32
int size = WideCharToMultiByte(CP_UTF8, 0, wcstr, -1, NULL, 0, NULL, NULL);
#else
size_t size = wcstombs(NULL, wcstr, 0);
#endif


mbstr = new char[size+1];
if (mbstr)
{
memset(mbstr, 0, size * sizeof(char));
#ifdef WIN32
int ret = WideCharToMultiByte(CP_UTF8, 0, wcstr, -1, mbstr, size, NULL, NULL);
if (ret == 0) // MultiByteToWideChar returns 0 if it does not succeed.
#else
size_t ret = wcstombs(mbstr, wcstr, size+1);
if (ret == -1)
#endif
{
delete[] mbstr;
mbstr = NULL;
}
}


return mbstr;
}


int main(int argc, char *argv[]){
setlocale(LC_ALL, "chs");//设置代码页,简体中文是936
SetConsoleOutputCP(936);


cout<<"string convert..`\nchar *\nwchar_t\n`\n"<<endl;


char *str = "long long ago, there is a girl, she\'s name is little redhat.";
cout<<"\nchar *str :\n"<<str<<endl;


//mbstowcs && wcstombs
// Convert to a wchar_t*


wchar_t *wstr;
wstr = mbs2wcs(str);
wcout<<"\nwchar_t *wstr : \n"<<wstr<<endl;


cout<<"sizeof(*str): "<<sizeof(*str)<<" byte"<<endl;  
cout<<"sizeof(*wstr): "<<sizeof(*wstr)<<" byte"<<endl;    //wstr指向第一个字符'l'占了16bit=2byte


return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值