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

kllll1119 2012-07-12 05:08:54

#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;
}


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

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

...全文
51 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
pathuang68 2012-07-12
  • 打赏
  • 举报
回复
用iconv吧,参考下面代码:

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

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧