I would like to print single Unicode characters to screen. I figured how to do it using std::wstring
, as I describe here. However, I would like to be able to use std::cout
consistently throughout my program (without need to switch to std::wcout
). Therefore, I am trying to convert from std::wstring
to utf-8 std::string
. All the posts asking about this conversion that I have read describe the usage of the header <codecvt>
. However, it was deprecated in C++17 and gives the run-time error
'std::wstring_convert<std::codecvt_utf8<wchar_t,1114111,0>,wchar_t,std::allocator<wchar_t>,std::allocator<char>>::to_bytes': warning STL4017: std::wbuffer_convert, std::wstring_convert, and the <codecvt> header (containing std::codecvt_mode, std::codecvt_utf8, std::codecvt_utf16, and std::codecvt_utf8_utf16) are deprecated in C++17. (The std::codecvt class template is NOT deprecated.) The C++ Standard doesn't provide equivalent non-deprecated functionality; consider using MultiByteToWideChar() and WideCharToMultiByte() from <Windows.h> instead. You can define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received this warning.
if you try to use any of its functionality.
This deprecation means we cannot any longer use accepted answers such as this, which suggests doing
#include <codecvt>
// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.to_bytes(str);
}
or this, which also relies on using codecvt.
The error I quoted above suggests using WideCharToMultiByte()
from the header <Windows.h>
. However, I am not an expert on encodings and I need some help to figure out how to use this. Could someone offer any help, or describe any alternate approaches?