linux 下 string 中文乱码问题解决

本文介绍了一个用于字符编码转换的C++实现案例,包括从UTF-8到GBK及反向转换的功能函数。通过具体示例展示了如何利用这些函数解决中文乱码问题。

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

以下是实现

#include <iconv.h>

extern std::vector<std::string> vecImageId;
int code_convert(char *from_charset, 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 (iconv(cd, pin, &inlen, pout, &outlen) == -1)
return -1;
iconv_close(cd);
*pout = '\0';


return 0;
}

//将UTF8转为GBK
int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
}

//将GBK转为UTF8
int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);

}


以下是使用:

std::string ObjExtVlprGLST::getVehStyle(std::string style)

{
char* str;
char outstr[128] = { 0 };
std::string str1 = "";
if (style == "1")
{
str = "轿车";
}
else if (style == "2")
{
str = "越野车";
}
g2u(str, strlen(str), outstr, 128);
str1 = outstr;
return str1;

}

这样可以解决中文乱码问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值