[英]Working with UTF-8 std::string objects in C++
我在Windows
上使用Visual Studio
和C++
來處理像ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ
這樣的小型大寫文本,例如使用這個網站。 每當我從文件中讀取此文本或使用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";
,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.