簡體   English   中英

在C ++流中使用UTF-8的正確和跨平台方式

[英]Correct and crossplatform way to use UTF-8 in C++ streams

從我對類似問題的答案中可以理解,Visual C ++ STL實現中仍然存在未修復的錯誤 因此,不可能只編寫std::cout << raw_utf8_string << std::endl並在Windows下享受漂亮的UTF-8字符;(

注意:我的測試程序住在這里

但是也許有一個很容易理解的解決方法來解決這個問題? 我的想法是:創建一個包裝類,如cout_ex ,它將使用Windows API WriteConsoleA進行控制台輸出。
在其構造函數中執行以下操作

#ifdef _WIN32
if (IsValidCodePage (CP_UTF8))
{
    if (!SetConsoleCP (CP_UTF8))
        std::cout << "Could not set console input code page to UTF-8" << std::endl;
    if (!SetConsoleOutputCP (CP_UTF8))
        std::cout << "Could not set console output code page to UTF-8" << std::endl;
}
else
    std::cout << "UTF-8 code page is not supported in your system" <<   std::endl;
#endif

並在輸出方法中執行以下操作:

char const raw_utf8_text[] = "Blåbærsyltetøy! кошка!";

DWORD raw_written = 0;
WriteConsoleA (GetStdHandle (STD_OUTPUT_HANDLE), raw_utf8_text, std::strlen (raw_utf8_text), &raw_written, NULL);

並且不要忘記在src的開頭使用未記錄的Visual C ++編譯指示:

#pragma execution_character_set("utf-8")

但是,也許有一個更清晰的解決方案:)即使使用了一些外部庫,例如Poco / Boost / etc。

我試着去閱讀這些文章12 ,但我發現這樣太復雜了。 PS Overrided流類也應將控制台字體設置為Unicode。
PPS軟件版本:Windows 8 x64 + Visual C ++ 2013 Express。

您應該在輸出流中注入適當的codecvt_facet。

std::locale loc;
string encoding=getOutputEncoding(); // 
loc=std::locale(loc, createCodecvt(encoding));
cout.imbue(loc);
cout.rdbuf().imbue(loc);

完整的代碼在這里

此構面應將內部編碼轉換為外部編碼。 由於STL實施中的某些錯誤 ,如果內部存儲格式為一字節或多字節編碼,則可能無法執行此操作。 有一種解決方法-使用filestreambuf代替默認輸出緩沖區。

您可能必須實現自己的codecvt_facet或使用我的iconv包裝器

總的來說,我仍然建議使用寬字符進行內部處理。 這樣,您甚至可以避免進行任何額外的轉換(系統默認轉換除外)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM