【千律】C++基础:宽窄字节字符串的相互转换与控制台输出

【千律】C++基础:宽窄字节字符串的相互转换与控制台输出,第1张

 方案1:
#include 
#include 
#include 
#include 
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 
#include 
#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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/674701.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-19
下一篇2022-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存