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