/*
* 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;
}
multi-byte wide-char
最新推荐文章于 2021-07-22 17:44:10 发布