Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

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

I'm using Visual Studio and C++ on Windows to work with small caps text like ʜᴇʟʟᴏ ꜱᴛᴀᴄᴋᴏᴠᴇʀꜰʟᴏᴡ using e.g. this website. Whenever I read this text from a file or put this text directly into my source code using std::string, the text visualizer in Visual Studio shows it in the wrong encoding, presumably the visualizer uses Windows (ANSI). How can I force Visual Studio to let me work with UTF-8 strings properly?

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
}

I tried the additional command line option /utf-8 for compiling and setting the locale:

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

Neither of those fixed the encoding issue.

Answer*

Draft saved
Draft discarded
Cancel
3
  • This may work for the text visualizer but it will not correct the code's encoding so it's only a semi solution. Still, you deserve your upvote. Commented Jan 31, 2020 at 22:45
  • @BullyWiiPlaza, what do you mean by the "the code's encoding"? Commented Jan 31, 2020 at 22:54
  • @R Sahu: I mean during processing of the code the string will not work correctly then. I e.g. copy the unicode text std::string object to the clipboard and when I paste it, it's screwed up. With a std::wstring version it works fine. Commented Feb 2, 2020 at 0:09

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /