C++ gbk与utf8互转

C++ gbk与utf8互转本文代码已在 vs2017 上验证 gbk 转 utf8 容易出现中文乱码 有的时候在 x8632 位编译环境下中文显示正常 但切换到 x6464 位编译环境下会乱码 本文所示的代码在 32 位和 64 位编译环境下均不会出现乱码 使用例子见 include iostream include stdlib h include string include string h include windows h usingnames windows h string h string stdlib h iostream

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

#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; }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233976.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号