我使用Visual Studio
,并C++
在Windows
与小型大写文字工作像ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ
例如使用这个网站。每当我从文件中读取此文本或使用将该文本直接放入我的源代码中时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());
这些都不能解决编码问题。
一个可行的解决方案是简单地将所有std::string
s 重写为std::wstring
s并适当地调整代码逻辑以使其与std::wstring
s一起使用,如问题中所示。现在一切正常。