吴先森的笔记
为退烧而生!
某咸鱼的笔记

Windows下C++实现UFT-8和GBK编码字符串互相转换

Windows下C++实现UFT-8和GBK编码字符串互相转换

最近,我想写一下我的API的客户端,供Windows开发者使用,可是在开发的时候遇到了一个问题:输出中文会乱码,仔细一想,感觉是编码的锅,cmd用UFT8编码后可以解决,于是我打算让其自动转换其字符类型

下面是代码,源于网上,找了好久找到的,修了几个bug和一些代码,仅供参考吧

#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;

string GbkToUtf8(const char* src_str)
{
	int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	string strTemp = str;
	if (wstr) delete[] wstr;
	if (str) delete[] str;
	return strTemp;
}

string Utf8ToGbk(const char* src_str)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0);
	wchar_t* wszGBK = new wchar_t[len + 1];
	memset(wszGBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, src_str, -1, wszGBK, len);
	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char* szGBK = new char[len + 1];
	memset(szGBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
	string strTemp(szGBK);
	if (wszGBK) delete[] wszGBK;
	if (szGBK) delete[] szGBK;
	return strTemp;
}


int main(void)
{
	const char* src_str = "这是一个测试";
	printf("\n源文本:");
	printf(src_str);
 
	printf("\ngbk to uft8:");
	printf(GbkToUtf8(src_str).c_str());

	printf("\nuft8 to gbk:");
	printf(Utf8ToGbk(src_str).c_str());
	return 0;
}

目前代码测试是没有问题的,如果有问题欢迎指出!

发表评论请先填写昵称和邮箱
评论需要审核后才能显示,与内容无关的评论、灌水评论、广告等不会通过审核
本站的所有教程均博主亲身尝试后的经验,且未注明的均为原创
本站的内容可能很小白化,老鸟勿喷。
本文链接:https://www.wunote.cn/article/1939/
本文采用 CC BY-NC-SA 3.0 Unported 协议进行许可

某摆烂咸鱼

文章作者

为退烧而生!

发表回复

textsms
account_circle
email

某咸鱼的笔记

Windows下C++实现UFT-8和GBK编码字符串互相转换
最近,我想写一下我的API的客户端,供Windows开发者使用,可是在开发的时候遇到了一个问题:输出中文会乱码,仔细一想,感觉是编码的锅,cmd用UFT8编码后可以解决,于是我打算让其自动转换…
扫描二维码继续阅读
2019-10-19