簡體   English   中英

在 C++ 中使用 UTF-8 std::string 對象

[英]Working with UTF-8 std::string objects in C++

我在Windows上使用Visual StudioC++來處理像ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ這樣的小型大寫文本,例如使用這個網站。 每當我從文件中讀取此文本或使用std::string將此文本直接放入我的源代碼時, Visual Studio中的文本可視化器都會以錯誤的編碼顯示它,大概是該可視化器使用Windows (ANSI) 如何強制Visual Studio讓我正確使用UTF-8字符串?

std::string message_or_file_path = "...";
auto message = message_or_file_path;

// If the file path is valid, read from that file
if (GetFileAttributes(message_or_file_path.c_str()) != INVALID_FILE_ATTRIBUTES
    && GetLastError() != ERROR_FILE_NOT_FOUND)
{
    std::ifstream file_stream(message_or_file_path);
    std::string text_file_contents((std::istreambuf_iterator<char>(file_stream)),
        std::istreambuf_iterator<char>());
    message = text_file_contents; // Displayed in wrong encoding
    message = "ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ"; // Displayed in wrong encoding
   std::wstring wide_message = L"ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ"; // Displayed in correct encoding
}

我嘗試了額外的命令行選項/utf-8來編譯和設置語言環境:

std::locale::global(std::locale(""));
std::cout.imbue(std::locale());

這些都沒有解決編碼問題。

Visual Studio 中我的 UTF-8 字符串出了什么問題? ,有幾種方法可以使用 UTF-8 編碼查看std::string的內容。

假設您有一個具有以下初始化的變量:

std::string s2 = "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9f\x8d\x8c";

使用觀察窗口。

  • 將變量添加到 Watch。
  • 在 Watch 窗口中,將,s8添加到變量名稱以將其內容顯示為 UTF-8。

這是我在 Visual Studio 2015 中看到的。

圖片

使用命令窗口。

  • 在命令行窗口中,使用? &s2[0],s8 ? &s2[0],s8將文本顯示為 UTF-8。

這是我在 Visual Studio 2015 中看到的。

圖片

一個可行的解決方案是簡單地將所有std::string s 重寫為std::wstring s 並正確調整代碼邏輯以使用std::wstring s,如問題中所示。 現在一切都按預期進行。

暫無
暫無

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

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