From 3da00c61b924de3e5236f5a450e535c8d32f1ea4 Mon Sep 17 00:00:00 2001 From: zhaohe Date: Tue, 26 Dec 2023 18:09:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AD=97=E7=AC=A6=E9=9B=86?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/iflytop/components/ziconv.cpp | 42 +++++++++++++++++++++++++++++++++++++++ src/iflytop/components/ziconv.hpp | 22 ++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/iflytop/components/ziconv.cpp create mode 100644 src/iflytop/components/ziconv.hpp diff --git a/src/iflytop/components/ziconv.cpp b/src/iflytop/components/ziconv.cpp new file mode 100644 index 0000000..6fa41b4 --- /dev/null +++ b/src/iflytop/components/ziconv.cpp @@ -0,0 +1,42 @@ +#include "utf8_to_gb2312.hpp" + +#include + +using namespace iflytop; + +string ZIconv::utf8_to_gb2312(const std::string& utf8_str) { + // 打开转换描述符 + iconv_t cd = iconv_open("GB2312", "UTF-8"); + if (cd == (iconv_t)-1) { + perror("iconv_open failed"); + exit(EXIT_FAILURE); + } + + // 输入字符串 + const char* in_str = utf8_str.c_str(); + size_t in_size = utf8_str.size(); + + // 输出缓冲区 + size_t out_size = in_size * 2; // 假设输出的字节数不会超过输入的两倍 + char* out_buf = new char[out_size]; + char* out_str = out_buf; + + // 进行转换 + if (iconv(cd, const_cast(&in_str), &in_size, &out_str, &out_size) == (size_t)-1) { + perror("iconv failed"); + iconv_close(cd); + delete[] out_buf; + exit(EXIT_FAILURE); + } + + // 关闭转换描述符 + iconv_close(cd); + + // 获取转换后的字符串 + std::string gb2312_str(out_buf, out_str - out_buf); + + // 释放内存 + delete[] out_buf; + + return gb2312_str; +} \ No newline at end of file diff --git a/src/iflytop/components/ziconv.hpp b/src/iflytop/components/ziconv.hpp new file mode 100644 index 0000000..dfbe516 --- /dev/null +++ b/src/iflytop/components/ziconv.hpp @@ -0,0 +1,22 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace iflytop { +using namespace std; + +class ZIconv { + private: + /* data */ + public: + static string utf8_to_gb2312(const string& utf8_str); +}; + +} // namespace iflytop \ No newline at end of file