首页 > 其他 > 详细

iconv 用法封装

时间:2014-07-18 11:15:18      阅读:338      评论:0      收藏:0      [点我收藏+]

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;
}


iconv 用法封装,布布扣,bubuko.com

iconv 用法封装

原文:http://blog.csdn.net/xseekerj/article/details/37918695

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!