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

 方案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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿飞_Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值