libiconv是常用库,直接上代码:

#include <iostream>
#include <string>
using namespace std;

#include <iconv.h>
#pragma comment(lib,"libiconv.dll.a")

wstring Ansi2Unicode(char* pm_AnsiText)
{
    const char* tocode = "UTF-16LE";
    const char* fromcode = "GBK";
    iconv_t cd = iconv_open(tocode, fromcode);
    if (cd == (iconv_t)-1)
    {
        return L"";
    }

    // iconv执行之后,inbuf指针变为未处理完的字符串首地址
    char* inbuf = pm_AnsiText;

    size_t inbytesleft = strlen(inbuf);
    size_t BUF_SIZE = inbytesleft * 2 + 2;

    // 转换后的字符串缓存
    char *outbuf = new char[BUF_SIZE];
    memset(outbuf, 0, BUF_SIZE);

    // iconv执行之后,outbuf指针变为剩余可用缓存空间的首地址
    // 转换完成的那部分,从outbuf的起始位置开始存储,因此要保存此指针的初始值
    char *ptr_orig_outbuf = outbuf;

    // 每次最多从inbuf读取inbytesleft字节进行转换
    // 每次最多将转换结果中的outbytesleft字节写入outbuf
    size_t outbytesleft = BUF_SIZE;

    // 没有做错误处理,未考虑包含无法转换字符的情况
    size_t st = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);

    // 取转换完成的字符串
    wstring wstrUnicodeText;
    wstrUnicodeText.append((wchar_t *)ptr_orig_outbuf, BUF_SIZE - outbytesleft);

    delete []ptr_orig_outbuf;
    outbuf = NULL;

    iconv_close(cd);

    return wstrUnicodeText;
}

int main()
{
    char *pText = "Chinese中国";

    wstring wstrUnicodeText = Ansi2Unicode(pText);
    wcout.imbue(std::locale("chs"));
    wcout << wstrUnicodeText << endl;

    return 0;
}
参考:
http://stackoverflow.com/search?q=libiconv
http://blog.csdn.net/hongchangfirst/article/details/8951391
http://www.360doc.com/content/13/0220/06/9200790_266670315.shtml
http://www.dongxf.com/6_Use_Iconv_To_Converse_Character_Sets.html
http://www.cppblog.com/izualzhy/archive/2012/12/21/196505.html
http://my.huhoo.net/archives/2008/02/libiconv.html


本文链接地址: iconv的基本使用方法
http://qingfengju.com/index.asp?id=379

分类:Win32/C++ 查看次数:6448 发布时间:2014-12-25 18:41:29