本例来源于CSDN的另一篇博客,但并非是复读机。原博客使用char类型作为输入,需要传递src_len和dst_len,用起来比较难受。本文使用std::string做了封装,不需要传递src_len和dst_len,代价就是在函数中动态分配了2src_len的空间。
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <iconv.h>
#include <fstream>
using namespace std;
bool encoding_convert(std::string const& src_str, std::string& dst_str,
std::string const& src_encoding, std::string const& dst_encoding)
{
iconv_t cd;
std::size_t src_len = src_str.size();
std::size_t dst_len = src_len * 2;
dst_str.resize(dst_len);
cd = iconv_open(dst_encoding.c_str(), src_encoding.c_str());
if (cd == 0)
return false;
char* src_data = (char*)(src_str.data());
char* dst_data = (char*)(dst_str.data());
std::size_t left_len {dst_len};
if (iconv(cd, &src_data, &src_len, &dst_data, &left_len) == -1)
return false;
iconv_close(cd);
dst_str.resize(dst_len-left_len);
return true;
}
char const* GBK = "gbk";
char const* UTF8 = "utf8";
#define GBK_2_UTF8(src_str, dst_str) encoding_convert(src_str, dst_str, GBK, UTF8)
#define UTF8_2_GBK(src_str, dst_str) encoding_convert(src_str, dst_str, UTF8, GBK)
int main(int argc, char* argv[]) {
std::string src = "\xc4\xe3\xba\xc3";
std::string dst;
std::fstream ofs("./result.txt", std::ios::out);
GBK_2_UTF8(src, dst);
std::cout << "Source GBK string:" << src << std::endl;
std::cout << "Result UTF8 String: " << dst << std::endl;
ofs << dst << std::endl;
std::cout << "========================================" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::string src1 = "你好,小黄鸡,小黄鸭,小黄狗";
std::string dst1;
UTF8_2_GBK(src1, dst1);
std::string res;
GBK_2_UTF8(dst1, res);
ofs << res << std::endl;
ofs.close();
std::cout << "Source UTF-8 string:" << src1 << std::endl;
std::cout << "Result GBK string:" << dst1 << std::endl;
std::cout << "Result UTF-8 string:" << res << std::endl;
return EXIT_SUCCESS;
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(chat_room)
add_definitions(-std=c++14)
find_package(Boost REQUIRED COMPONENTS
system
filesystem
serialization
program_options
thread
)
include_directories(${Boost_INCLUDE_DIRS})
file( GLOB APP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.h)
foreach( sourcefile ${APP_SOURCES} )
file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${sourcefile})
if( "${filename}" STREQUAL "main.cpp")
string(REPLACE ".cpp" "" file ${filename})
add_executable(${file} ${APP_SOURCES})
target_link_libraries(${file} ${Boost_LIBRARIES})
target_link_libraries(${file} pthread)
endif()
endforeach( sourcefile ${APP_SOURCES})
程序输出如下,
![在这里插入图片描述](https://img-blog.csdnimg.cn/5725df21157b4f6dabb7a6e8ccfed149.png)
result.txt文件内容如下,
![在这里插入图片描述](https://img-blog.csdnimg.cn/0c2d4ef0fd2e4f8cb88fa8e6e7307d1c.png)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)