C/C++教程

C++ gbk与utf8互转

本文主要是介绍C++ gbk与utf8互转,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文代码已在vs2017上验证。gbk转utf8容易出现中文乱码,有的时候在x86 32位编译环境下中文显示正常,但切换到x64 64位编译环境下会乱码。本文所示的代码在32位和64位编译环境下均不会出现乱码。使用例子见:。

#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <windows.h>

using namespace std;

string GBK_2_UTF8(string gbkStr)
{
	string outUtf8 = "";
	int n = MultiByteToWideChar(CP_ACP, 0, gbkStr.c_str(), -1, NULL, 0);
	WCHAR *str1 = new WCHAR[n];
	MultiByteToWideChar(CP_ACP, 0, gbkStr.c_str(), -1, str1, n);
	n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
	char *str2 = new char[n];
	WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
	outUtf8 = str2;
	delete[]str1;
	str1 = NULL;
	delete[]str2;
	str2 = NULL;
	return outUtf8;
}

string UTF8_2_GBK(string utf8Str)
{
	string outGBK = "";
	int n = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, NULL, 0);
	WCHAR *str1 = new WCHAR[n];
	MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, str1, n);
	n = WideCharToMultiByte(CP_ACP, 0, str1, -1, NULL, 0, NULL, NULL);
	char *str2 = new char[n];
	WideCharToMultiByte(CP_ACP, 0, str1, -1, str2, n, NULL, NULL);
	outGBK = str2;
	delete[] str1;
	str1 = NULL;
	delete[] str2;
	str2 = NULL;
	return outGBK;
}

这篇关于C++ gbk与utf8互转的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!