void encode_convert(iconv_t& cd, const char* str, size_t str_len,
        std::string* out)
{
    char utf_buf[kMaxCoding] = {0};
    char* pout = utf_buf;
    char* pin = const_cast<char*>(str);
    size_t from_len = str_len;
    size_t to_len = sizeof(utf_buf);
    if (iconv(cd, &pin, &from_len, &pout, &to_len) == (size_t) -1)
    {
        fprintf(stderr, "convert for %s", str);
    }
    out->assign(utf_buf);
}

这段代码没问题,运行得很好,但后来 kMaxCoding 定义在其它文件中了,所以我把它作为参数传递过来了,但编译无法过。

只能修改成为这样

void encode_convert(iconv_t& cd, const char* str, size_t str_len,
        std::string* out, const size_t max_coding_size)
{
    char utf_buf[max_coding_size];
    utf_buf[0] = '\0'; //trick
    char* pout = utf_buf;
    char* pin = const_cast<char*>(str);
    size_t from_len = str_len;
    size_t to_len = sizeof(utf_buf);
    if (iconv(cd, &pin, &from_len, &pout, &to_len) == (size_t) -1)
    {
        fprintf(stderr, "convert for %s", str);
    }
    out->assign(utf_buf);
}

但此时就会在转换后的string中多一个y 字符串。

如果将标黄的代码转换为 memset(utf_buf, 0, sizeof(utf_buf));就会没问题了,我想应该是转码可能没有加\0什么的。

 

 

在查看了 在Linux下使用iconv转换字符串编码 的iconv接口函数说明后,我将assign 段修改为

out->assign(utf_buf, sizeof(utf_buf) - to_len);

清净了。

相关文章:

  • 2021-06-27
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2021-12-16
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
相关资源
相似解决方案