关于C++解析utf-8字符流的乱码问题

nizainade 2010-10-13 09:48:07
问题是这样的,远端是java编写的server端,我这边client通过TCP连接server端后,远端会发送utf-8编码格式的字符流,我用 recv接收发现,中文是乱码。然后我就从网上搜索,发现是编码问题,从网上搜到一篇帖子:

http://www.cppblog.com/boymaster/articles/7020.html

关于utf-8和gbk编码的转换的,但是我把recv到的字符数组用UTF_8ToGB2312函数转换了后,打印出来还是乱码??请问大侠们怎么回事?socket的本端recv的时候这样解析对否?

本端是C++写的
...全文
213 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
老邓 2010-10-14
  • 打赏
  • 举报
回复
如果你本地程序是UNICODE编码的话,你需要先转换到ANSI,再从ANSI转换到UNICODE。
#include <windows.h>
#include <iostream>
#include <vector>

using namespace std;

std::wstring UT2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
std::vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);

return std::wstring(&unicode[0]);
}

std::string WC2UT(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
std::vector<char> utf8(len);
WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);

return std::string(&utf8[0]);
}

std::wstring MB2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
std::vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);

return std::wstring(&unicode[0]);
}

std::string WC2MB(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
std::vector<char> utf8(len);
WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL);

return std::string(&utf8[0]);
}

int main()
{
setlocale(LC_ALL, "");

const wchar_t* s1 = L"UNICODE转换成UTF-8";
cout << WC2UT(s1).c_str() << endl;

const char* s2 = "ANSI转换成UNICODE";
wcout << MB2WC(s2).c_str() << endl;

const wchar_t* s3 = L"UNICODE转换成ANSI";
cout << WC2MB(s3).c_str() << endl;

return 0;
}
iambic 2010-10-13
  • 打赏
  • 举报
回复
自己研究下接受到的字节,转换后的字节,看看到底是不是UTF8和GBK的。可以把字节贴出来看下(别用UltraEdit贴)。
mymtom 2010-10-13
  • 打赏
  • 举报
回复
推荐用iconv

64,649

社区成员

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

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