[轉]深入 printf / wprintf / console下的unicode output
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);
會有正確的輸出
綜上:?
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,但是跨平臺,大多數情況會工作得很好。
posted on 2006-06-22 02:11
Jerry Cat 閱讀(466)
評論(0) 編輯 收藏 引用