码迷,mamicode.com
首页 > 其他好文 > 详细

iconv 用法封装

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

标签:blog   os   2014   for   re   c   

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 用法封装

标签:blog   os   2014   for   re   c   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!