Windows下printf能够直接打印UTF-16字符串吗?

feng32tc 2011-09-08 04:24:25
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
TCHAR szUtf16[100] = TEXT("Hello你好!");
char szGb2312[100];

SetConsoleOutputCP(936); // GB2312

_tprintf(TEXT("%s\n"), szUtf16);
_tprintf(TEXT("%ls\n"), szUtf16);
_tprintf(TEXT("%hs\n"), szUtf16);

_getch();

SetConsoleOutputCP(1200); // UTF-16

_tprintf(TEXT("%s\n"), szUtf16);
_tprintf(TEXT("%ls\n"), szUtf16);
_tprintf(TEXT("%hs\n"), szUtf16);

_getch();

SetConsoleOutputCP(936); // GB2312

WideCharToMultiByte(936, 0, szUtf16, -1, szGb2312, 100, 0, 0);
_tprintf(TEXT("%S\n"), szGb2312);

_getch();

return 0;
}



问题如上,试了很多种组合都不行。一定要使用WideCharToMultiByte转换到本地单字节编码才能正常显示吗?
...全文
624 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackyjkchen 2011-09-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 feng32tc 的回复:]

问题解决了。关键是要调用 setlocale(LC_ALL, ""),否则还是问号。SetConsoleOutputCP似乎完全没效果。

不过很奇怪为什么还要手动把locale重置为默认值。

C/C++ code
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
//Sets the locale to ……
[/Quote]

打印宽字符的时候确实得要,主要是Windows的cmd默认是gbk编码的(中文版的话,其实就是本地语言编码)

你输出到文件就不要了

feng32tc 2011-09-08
  • 打赏
  • 举报
回复
问题解决了。关键是要调用 setlocale(LC_ALL, ""),否则还是问号。SetConsoleOutputCP似乎完全没效果。

不过很奇怪为什么还要手动把locale重置为默认值。

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
//Sets the locale to the default, which is the user-default ANSI code page obtained from the operating system.
setlocale( LC_ALL, "" );

TCHAR szUtf16[100] = TEXT("Hello你好!");

SetConsoleOutputCP(936); // GB2312

_tprintf(TEXT("%s\n"), szUtf16);
_tprintf(TEXT("%ls\n"), szUtf16);

_getch();

SetConsoleOutputCP(1200); // UTF-16

_tprintf(TEXT("%s\n"), szUtf16);
_tprintf(TEXT("%ls\n"), szUtf16);

_getch();

return 0;
}
jackyjkchen 2011-09-08
  • 打赏
  • 举报
回复
一定要用TCHAR

如下

TCHAR是为了配合Windows的双版本API的,不同工程属性,TCHAR不一样

#include <stdio.h>
#include <tchar.h>
#include <locale.h>


int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "");
WCHAR szUtf16[] = L"Hello你好!";
wprintf(L"%s\n", szUtf16);

printf("%S\n", szUtf16);

TCHAR szT[] = _T("Hello你好!");
_tprintf(_T("%s\n"), szT);

getchar();
return 0;
}


AndyZhang 2011-09-08
  • 打赏
  • 举报
回复
可以啊
jackyjkchen 2011-09-08
  • 打赏
  • 举报
回复
楼主没明白TCHAR的意义,TCHAR不一定是WCHAR

给你两种解决方案

都可以,printf和wprintf都能打印宽字符


#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "");
WCHAR szUtf16[] = L"Hello你好!";
wprintf(L"%s\n", szUtf16);

printf("%S\n", szUtf16);
getchar();
return 0;
}


69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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