首页 > 代码库 > iconv 用法封装
iconv 用法封装
std::string iconv_convert(const std::string& in, const char* fromcode, const char* tocode) { char buffer[128]; std::string out; auto cd = iconv_open(tocode, fromcode); if (cd != nullptr) { size_t outbytesleft = sizeof(buffer); size_t inbytesleft = in.size(); const char* inbuf = in.c_str(); char* outbuf = buffer; int ret = 0; for (;;) { ret = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft); if (0 == ret) { out.insert(out.end(), buffer, buffer + sizeof(buffer)-outbytesleft); break; } else { assert(inbytesleft > 0); assert(outbytesleft == 0); out.insert(out.end(), buffer, buffer + sizeof(buffer)); outbytesleft = sizeof(buffer); outbuf = buffer; } } } else { return out; } (void)iconv_close(cd); return out; } /// example int main(int, char**) { std::string utf8str = iconv_convert("你好吗", "gb2312", "utf-8"); return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。