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

nizainade 2010-10-13 09:38: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的时候这样解析对否?
...全文
380 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
nizainade 2010-10-14
  • 打赏
  • 举报
回复
你说的本地程序的编码是指开发环境的编码吗??我那是接受中文的时候是乱码,能转换为ansi编码吗?


我从 网上搜到的从utf-8转换到gbk的函数,解析的都不行。
老邓 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;
}
nizainade 2010-10-13
  • 打赏
  • 举报
回复
我本端是c++的

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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