读书人

一个GBK转UTF8的有关问题求教高手

发布时间: 2012-09-24 13:49:42 作者: rapoo

一个GBK转UTF8的问题,求教高手

C/C++ code
#include <iostream>#include <string>#include <windows.h>using namespace std;string GBKToUTF8(const string& strGBK){    string strOutUTF8 = "";    WCHAR * str1;    int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);    str1 = new WCHAR[n];    MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);    n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);    char * str2 = new char[n];    WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);    strOutUTF8 = str2;    delete[]str1;    str1 = NULL;    delete[]str2;    str2 = NULL;    return strOutUTF8;}void main(){    cout << GBKToUTF8("队<") << endl;    cout << GBKToUTF8("队") << endl;    string str = GBKToUTF8("队");    cout << str+"<" << endl;} 


运行结果:
//打不来那个字,用星号代替
*?
*
*?

感觉那个字符和'<' 连在一起就变问号了,这个怎么处理啊,想正常显示'<'



[解决办法]
用iconv吧,参考下面代码:
C/C++ code
#include <iconv.h>#pragma comment(lib,"iconv.lib") int code_convert(char *from_charset,char *to_charset,const char *inbuf, size_t inlen,char *outbuf, size_t outlen){         iconv_t cd;         const 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);         return 0;} /* UTF-8 to GBK  */int u2g(const char *inbuf, size_t inlen, char *outbuf, size_t outlen){         return code_convert("UTF-8","GBK",inbuf,inlen,outbuf,outlen);} /* GBK to UTF-8 */int g2u(const char *inbuf, size_t inlen, char *outbuf, size_t outlen){         return code_convert("GBK", "UTF-8", inbuf, inlen, outbuf, outlen);} 

读书人网 >C++

热点推荐