iconv 的参数问题

工作中遇到一个转码的问题,如下代码说话

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);

清净了。

posted @ 2015-04-08 16:25  westfly  阅读(468)  评论(0编辑  收藏  举报