C++ gbk与utf8互转
C++ utf8 互转 GBK
2023-09-27 14:27:52 时间
本文代码已在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;
}
相关文章
- C++-std:tuple元组的基本用法
- 2022-02-18 编译并使用protobuf完成c++序列化
- 《挑战30天C++入门极限》C++的iostream标准库介绍(2)
- 数据结构 - 双链表(C++)
- 深入分析C++引用
- c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法&提示缺少“libmysql.dll”
- vc++高级班之窗口篇[4]---让程序只运行一个实例
- C++ 获取类成员函数地址方法 浅析
- C++11多线程教学(二)
- Visual C++ unicode and utf8 转换
- C++11 新特性总结
- 初学C++,坚决不能挂!
- 国外程序员整理的 C++ 资源大全