首页 > 代码库 > 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;
}