1.使用WideCharToMultiByte和MultiByteToWideChar;
2.使用mbstowcs_s和wcstombs_s(vs中添加_s);
3.使用c++11提供的wstring_convert
demo:程序如下
下载地址https://pan.baidu.com/s/1yBRYKuRBMLkeMO3v1LJZjg 提取码:oh3t
#include “iostream”
#include “string”
#include “locale.h”
#include
#include “windows.h”
using namespace std;
//string 与 wstring之间的转换
string ws2s(const wstring &ws)
{
//setlocale需要头文件#include “locale.h”
string curLocale = setlocale(LC_ALL, NULL);
setlocale(LC_ALL, “chs”);
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char* _Dest = new char[_Dsize];
memset(_Dest, 0, _Dsize);
//wcstombs(_Dest, _Source, _Dsize); 为避免error C4996警告
size_t len = 0;
wcstombs_s(&len, _Dest, _Dsize, _Source, _TRUNCATE);
string result = _Dest;
delete[] _Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
wstring s2ws(const string &s)
{
string curLocale = setlocale(LC_ALL, NULL);
setlocale(LC_ALL, “chs”);
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t* _Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
size_t len = 0;
mbstowcs_s(&len, _Dest, _Dsize, _Source, _TRUNCATE);
wstring result = _Dest;
delete[] _Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
//char* 与 wchar_t* 之间的转换
char* wctoc(const wchar_t* str)
{
if (str == NULL)
{
return NULL;
}
DWORD num = WideCharToMultiByte(CP_ACP,0,str,-1,NULL,0,NULL,NULL);
char* pRes = new char[num];
WideCharToMultiByte(CP_ACP, 0, str, -1, pRes, num, NULL, NULL);
return pRes;
}
wchar_t* ctowc(const char* str)
{
if (str == NULL)
{
return NULL;
}
DWORD num = MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
wchar_t* pRes = new wchar_t[num];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, str, -1, pRes, num);
return pRes;
}
int main()
{
//string wstring 间转换
string s = “12345”;
wstring ws = s2ws(s);
wchar_t buf[20] = { 0 };
ws.copy(buf, ws.size(), 0);
wprintf(L"test s2ws:%ws\n", buf);
wstring ws2 = L"12345";
string s2 = ws2s(ws2);
char buf2[20] = { 0 };
s2.copy(buf2, s2.size(), 0);
printf("test ws2s:%s\n", buf2);
//char* 与wchar_t* 之间转换
const wchar_t* ws3 = L"abcde";
const char* s3 = wctoc(ws3);
printf("test2 wctoc: %s\n", s3);
delete[] s3;
s3 = NULL;
const char* s4 = "abcde";
const wchar_t* ws4 = ctowc(s4);
wprintf(L"test2 ctowc:%ws", ws4);
delete[] ws4;
ws4 = NULL;
wstring ws5{ L"Hello world." };
string s5;
// 声明一个用于转换的变量cv。所有的转换都经过此变量。
//头文件#include
wstring_convert> cv;
s5 = cv.to_bytes(ws5);// 宽字节转多字节
printf("test3 ws to s:%s\n", s5.c_str());
string s6("helloworld");
wstring ws6 = cv.from_bytes(s6);// 多字节转宽字节
wprintf(L"test4 s to ws:%ws\n", ws6.c_str());
return 0;
}