Linux下C++通过iconv实现字符集UTF8和GBK互转

这个程序实现了C++中UTF-8和GBK编码间的转换。主要函数code_convert用于通用的编码转换,u2g和g2u分别用于UTF-8到GBK和GBK到UTF-8的转换。GBKToUTF8和UTFtoGBK为字符串对象的转换包装。在main函数中,展示了转换过程,并验证了转换的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iconv.h>
#include <iostream>
#include <string.h>
#include <malloc.h>

int code_convert(const char *from_charset, const char *to_charset, char *inbuf, size_t inlen,
                 char *outbuf, size_t outlen) {
    iconv_t cd;
    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open(to_charset, from_charset);
    if (cd == 0)
        return -1;

    memset(outbuf, 0, outlen);

    if ((int)iconv(cd, pin, &inlen, pout, &outlen) == -1)
    {
        iconv_close(cd);
        return -1;
    }
    iconv_close(cd);
    *pout = '\0';

    return 0;
}

int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
}

int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);
}

std::string GBKToUTF8(const std::string& strGBK)
{
    int length = strGBK.size()*2+1;

    char *temp = (char*)malloc(sizeof(char)*length);

    if(g2u((char*)strGBK.c_str(),strGBK.size(),temp,length) >= 0)
    {
        std::string str_result;
        str_result.append(temp);
        free(temp);
        return str_result;
    }else
    {
        free(temp);
        return "";
    }
}

std::string UTFtoGBK(const char* utf8)
{
    int length = strlen(utf8);

    char *temp = (char*)malloc(sizeof(char)*length);

    if(u2g((char*)utf8,length,temp,length) >= 0)
    {
        std::string str_result;
        str_result.append(temp);
        free(temp);

        return str_result;
    }else
    {
        free(temp);
        return "";
    }
}

int main()
{
    std::string teststr = "测试字符串";

    std::cout<< "原始字符串:" << teststr.c_str() << std::endl;

    std::cout<< "UTF8转换GBK后的字符串:" << UTFtoGBK(teststr.c_str()).c_str() << std::endl;

    std::cout<< "GBK转换UTF8后的字符串:" << GBKToUTF8(UTFtoGBK(teststr.c_str()).c_str()).c_str() << std::endl;

    getchar();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值