mbstowcs和wcstombs函数 ?

aeolus_boy 2010-12-21 01:47:49

7 int main(int argc,char** argv){
8 std::string str = "qilov我e爱你中国";
9 wchar_t w_char[10000];
10
11 setlocale(LC_ALL,"zh_CN.utf8");
12 mbstowcs(w_char,str.c_str(),str.size());
13 std::wstring w_str(w_char);
14
15 //w_str.erase(w_str.begin()+8,w_str.end());
16
17 std::wcout<< w_str.size() <<std::endl;
18 std::wcout<< w_str <<std::endl;
19
20 wcstombs(&str[0],w_str.c_str(),w_str.size() * 3);
21
22 std::cout << str <<std::endl;
23
24 return EXIT_SUCCESS;
25 }




运行结果:

11
qilov我e爱你中国
mbstowcs能成功!但再转换回去wcstombs就不行了!
20行和22行没效果!唉,我都疲倦了!
...全文
275 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aeolus_boy 2010-12-22
  • 打赏
  • 举报
回复

18 std::wcout<< w_str <<std::endl
22 std::cout << str <<std::endl;


这两句有问题
luciferisnotsatan 2010-12-21
  • 打赏
  • 举报
回复
mbstowcs(w_char,str.c_str(),str.size()+1);
或者size加上1,size不包含最后的结束符 \0。因此你的代码之转换了字符串,但把最后的 \0 漏了。
luciferisnotsatan 2010-12-21
  • 打赏
  • 举报
回复
wchar_t w_char[10000] = {0};
初始化下
龙哥依旧 2010-12-21
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

void main( void )
{
int i;
char *pmbbuf = (char *)malloc( MB_CUR_MAX );
wchar_t *pwchello = L"Hello, world.";

printf( "Convert wide-character string:\n" );
i = wcstombs( pmbbuf, pwchello, MB_CUR_MAX );
printf( "\tCharacters converted: %u\n", i );
printf( "\tMultibyte character: %s\n\n", pmbbuf );
}
龙哥依旧 2010-12-21
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>

void main( void )
{
int i;
char *pmbnull = NULL;
char *pmbhello = (char *)malloc( MB_CUR_MAX );
wchar_t *pwchello = L"Hi";
wchar_t *pwc = (wchar_t *)malloc( sizeof( wchar_t ));

printf( "Convert to multibyte string:\n" );
i = wcstombs( pmbhello, pwchello, MB_CUR_MAX );
printf( "\tCharacters converted: %u\n", i );
printf( "\tHex value of first" );
printf( " multibyte character: %#.4x\n\n", pmbhello );

printf( "Convert back to wide-character string:\n" );
i = mbstowcs( pwc, pmbhello, MB_CUR_MAX );
printf( "\tCharacters converted: %u\n", i );
printf( "\tHex value of first" );
printf( " wide character: %#.4x\n\n", pwc );
}
dengsf 2010-12-21
  • 打赏
  • 举报
回复
setlocale 确定已调用成功?

另外,控制台输出也有编码问题的,
试试输出到文件,或断点调试查看内存值,看wcstombs是否能正确转换。
aeolus_boy 2010-12-21
  • 打赏
  • 举报
回复
深夜了,你们都睡了。我还在弄的!始终不能输出

64,649

社区成员

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

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