用WideCharToMultiByte转化完的字符串为什么后面还跟着些乱码??

cl781121 2009-05-18 02:25:37
转化已经对了,在正确的字符串后面总是跟着些乱码

例如
cstring gg = "测试实验"
wchar_t *tt = gg.c_str();
int cc = szLine.GetLength();
char* yye = new char[cc];
wchar_t* sz = szLine.GetBuffer();
::WideCharToMultiByte(CP_ACP,0,sz,-1, yye, cc, NULL, NULL);
这个时候 yye ="测试实验 铪铪" 多了后面的一大段空格和乱码

...全文
134 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
kusey 2009-05-18
  • 打赏
  • 举报
回复

char* yye = NULL;
DWORD dwNum = WideCharToMultiByte(CP_ACP,0,sz,-1, NULL, 0, NULL, NULL);
yye = new char[dwNum];
::WideCharToMultiByte(CP_ACP,0,sz,-1, yye, dwNum, NULL, NULL);
「已注销」 2009-05-18
  • 打赏
  • 举报
回复
你需要先获取转换后的字符串长度!
给你参考一下我工程里的转换函数:

shared_ptr<wstring> UT2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
if (len == 0) return shared_ptr<wstring>(new wstring(L""));

vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);

return shared_ptr<wstring>(new wstring(&unicode[0]));
}

shared_ptr<string> WC2UT(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
if (len == 0) return shared_ptr<string>(new string(""));

vector<char> utf8(len);
WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);

return shared_ptr<string>(new string(&utf8[0]));
}

shared_ptr<wstring> MB2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
if (len == 0) return shared_ptr<wstring>(new wstring(L""));

vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);

return shared_ptr<wstring>(new wstring(&unicode[0]));
}

shared_ptr<string> WC2MB(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
if (len == 0) return shared_ptr<string>(new string(""));

vector<char> utf8(len);
WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL);

return shared_ptr<string>(new string(&utf8[0]));
}
长安宁 2009-05-18
  • 打赏
  • 举报
回复
char* yye = new char[cc];
至少这里是错的,new char[cc+1];
wangyadong 2009-05-18
  • 打赏
  • 举报
回复
char* yye = new char[cc];
memset(yye,cc,' ');
wangyadong 2009-05-18
  • 打赏
  • 举报
回复
没有初始化
可以用memset初始化一下
cl781121 2009-05-18
  • 打赏
  • 举报
回复
上面写错了szLine 换成 gg


cstring gg = "测试实验"
wchar_t *tt = gg.c_str();
int cc = gg.GetLength();
char* yye = new char[cc];
wchar_t* sz = gg.GetBuffer();
::WideCharToMultiByte(CP_ACP,0,sz,-1, yye, cc, NULL, NULL);
这个时候 yye ="测试实验 铪铪" 多了后面的一大段空格和乱码

65,211

社区成员

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

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