Posted on 2006-06-21 11:53
小明 閱讀(18400)
評(píng)論(5) 編輯 收藏 引用 所屬分類:
C/C++ 、
G11N/ICU
1. printf 只能提供ANSI/MB 的輸出,不支持輸出unicode stream.
例如:
wchar_t?test[]=L"測(cè)試1234";
printf("%s",test);
是不會(huì)正確輸出的
2.wprintf 同樣不會(huì)提供unicode output,
?? 但是他會(huì)把wchar_t的string轉(zhuǎn)為locale的SB/MB字符編碼,然后輸出
例如:
wchar_t?test[]?=?L"測(cè)試Test";
wprintf(L"%s",test);
會(huì)輸出??1234之類的字符串,或者不輸出任何結(jié)果
因?yàn)閣printf沒有辦法把L"測(cè)試Test"轉(zhuǎn)為默認(rèn)的ANSI,需要設(shè)置locale
setlocale(LC_ALL,"chs");
wchar_t?test[]?=?L"測(cè)試Test";
wprintf(L"%s",test);
會(huì)有正確的輸出
等同于printf("%ls",test);
綜上:?
CRT I/O functions do not provide Unicode output.
3. Window console自從NT4就是一個(gè)真正的unicode console
不過輸出unicode string,只有使用Windows API, WriteConsoleW
例如:
wchar_t?test[]?=?L"測(cè)試1234";
DWORD?ws;
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),test,wcslen(test),&ws,NULL);
可以正確的輸出而不需要設(shè)置locale,因?yàn)槭钦嬲膗nicode的輸出,跟codepage無關(guān)
4. 如何實(shí)現(xiàn)跨平臺(tái)的console output
??? 不要使用wchar_t和wprintf,因?yàn)檫@些都依賴于編譯器.
???? ICU是IBM的一個(gè)成熟的跨平臺(tái)支持unicode的libary,推薦使用
以下是ICU的uprintf實(shí)現(xiàn)
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轉(zhuǎn)化為本地的codepage,然后printf,雖然也不是unicode output,但是跨平臺(tái),大多數(shù)情況會(huì)工作得很好。