【发布时间】:2020-02-01 08:40:32
【问题描述】:
我在Windows 上使用Visual Studio 和C++ 来处理像ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ 这样的小型大写字母文本,例如使用this 网站。每当我从文件中读取此文本或使用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());
这些都没有解决编码问题。
【问题讨论】:
-
.cpp文件的编码是什么?
-
您应该以二进制模式打开
std::ifstream,以避免在读取chars 时发生任何数据转换。这至少可以确保std::string具有正确的字节。不过,这并不意味着 IDE 会正确显示它。否则,请改用std::wstring,正如您已经发现的那样。您可以使用带有 UTF-8 语言环境imbue()的std::wifstream来阅读它。或者先读取原始字节,然后使用MultiByteToWideChar()或std::wstring_convert将字节转换为std:::wstring
标签: c++ windows visual-studio encoding utf-8