方案1:
#include <string>
#include <tchar.h>
#include <iostream>
#include <windows.h>
using namespace std;
// 窄字节转换为宽字节
wchar_t* str_a2w(char* str_a)
{
// 计算字节所需长度
int str_a_len = MultiByteToWideChar(CP_ACP, 0, str_a, -1, NULL, 0);
// 判断字符长度读取是否成功
if (str_a_len <= 0) return NULL;
// 动态申请内存并置0
wchar_t* str_w = new wchar_t[str_a_len];
wmemset(str_w, 0, str_a_len);
// 窄字节到宽字节的转换
MultiByteToWideChar(CP_ACP, 0, str_a, -1, str_w, str_a_len);
// 返回结果
return str_w;
}
// 宽字节转换为窄字节
char* str_w2a(wchar_t* str_w)
{
// 计算字节所需长度
int str_w_len = WideCharToMultiByte(CP_ACP, 0, str_w, -1, NULL, 0, NULL, NULL);
// 判断字符长度读取是否成功
if (str_w_len <= 0) return NULL;
// 动态申请内存并置0
char* str_a = new char[str_w_len];
memset(str_a, 0, str_w_len);
// 宽字节到窄字节的转换
WideCharToMultiByte(CP_ACP, 0, str_w, -1, str_a, str_w_len, NULL, NULL);
// 返回结果
return str_a;
}
int main()
{
// 初始化
wchar_t* point_wstr = L"梦想中国2022";
// 宽字节转换为窄字节
char* point_w2a = str_w2a(point_wstr);
// 窄字节转换为宽字节
wchar_t* point_a2w = str_a2w(point_w2a);
// 解决控制台不输出中文问题
wcout.imbue(std::locale("chs"));
// 输出结果
cout << "转换后结果 = " << point_w2a << endl;
wcout << L"转换后结果 = " << point_a2w << endl;
// 删除申请内存
delete[] point_w2a;
delete[] point_a2w;
return 0;
}
方案2:
#include <tchar.h>
#include <iostream>
#include "atlbase.h"
#include "atlstr.h"
using namespace std;
int main()
{
// 初始化
wchar_t* point_wstr = L"梦想中国2022";
// 宽字节转换为窄字节
CW2A point_w2a(point_wstr);
char* str_a = (char*)point_w2a;
// 窄字节转换为宽字节
CA2W point_a2w(point_w2a);
wchar_t* str_w = (wchar_t*)point_a2w;
// 解决控制台不输出中文问题
wcout.imbue(std::locale("chs"));
// 输出结果
cout << "转换后结果 = " << str_a << endl;
wcout << L"转换后结果 = " << str_w << endl;
return 0;
}