温馨提示:本文翻译自stackoverflow.com,查看原文请点击:windows - Working with UTF-8 std::string objects in C++
c++ encoding utf-8 visual-studio windows

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

发布于 2020-04-08 00:10:46

我使用Visual Studio,并C++Windows与小型大写文字工作像ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ例如使用这个网站。每当我从文件中读取此文本或使用将该文本直接放入我的源代码中时std::string,文本可视化工具Visual Studio都会以错误的编码显示它,大概是可视化工具使用的Windows (ANSI)如何强迫Visual StudioUTF-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());

这些都不能解决编码问题。

查看更多

提问者
BullyWiiPlaza
被浏览
64
BullyWiiPlaza 2020-02-01 06:40

一个可行的解决方案是简单地将所有std::strings 重写std::wstrings并适当地调整代码逻辑以使其与std::wstrings一起使用,如问题中所示。现在一切正常。