深入 printf / wprintf / console下的unicode output

深入 printf / wprintf / console下的unicode output
Posted on 2006-06-21 11:53 小明 阅读(458) 评论(2) 编辑 收藏 收藏至365Key 所属分类: C/C++ 、G11N/ICU
1. printf 只能提供ANSI/MB 的输出,不支持输出unicode stream.
例如:
wchar_t test[]=L”测试1234″;
printf(“%s”,test);是不会正确输出的

2.wprintf 同样不会提供unicode output,
但是他会把wchar_t的string转为locale的SB/MB字符编码,然后输出
例如:
wchar_t test[] = L”测试Test”;
wprintf(L”%s”,test);会输出??1234之类的字符串,或者不输出任何结果
因为wprintf没有办法把L”测试Test”转为默认的ANSI,需要设置locale
setlocale(LC_ALL,”chs”);
wchar_t test[] = L”测试Test”;
wprintf(L”%s”,test);会有正确的输出
等同于printf(“%ls”,test);

综上: CRT I/O functions do not provide Unicode output.

3. Window console自从NT4就是一个真正的unicode console
不过输出unicode string,只有使用Windows API, WriteConsoleW
例如:
wchar_t test[] = L”测试1234″;
DWORD ws;
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),test,wcslen(test),&ws,NULL);可以正确的输出而不需要设置locale,因为是真正的unicode的输出,跟codepage无关

4. 如何实现跨平台的console output
不要使用wchar_t和wprintf,因为这些都依赖于编译器.
ICU是IBM的一个成熟的跨平台支持unicode的libary,推荐使用

以下是ICU的uprintf实现

void uprintf(const UnicodeString &str) {
char *buf = 0;
int32_t len = str.length();
int32_t bufLen = len + 16;
int32_t actualLen;
buf = new char[bufLen + 1];
actualLen = str.extract(0, len, buf/*, bufLen*/); // Default codepage conversion
buf[actualLen] = 0;
printf(“%s”, buf);
delete buf;
}它也是先把Unicode string转化为本地的codepage,然后printf,虽然也不是unicode output,但是跨平台,大多数情况会工作得很好。

随机日志

发表评论

0 评论.

Leave a Reply



[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

CNXCT小组的博客 is Stephen Fry proof thanks to caching by WP Super Cache