I am very new to C++. I want to read a UTF-16 text file in C++17 in Visual Studio 2019.
I have tried several methods in the internet (including StackOverflow) but none of them worked, and some of them didn't compile (I think they only support older compilers).
I am trying to achieve this without using any 3rd party libraries.
This reads a text file, but it has some weird characters and spaces between each letter.
// open file for reading
std::wifstream istrm(filename, std::ios::binary);
if (!istrm.is_open()) {
std::cout << "failed to open " << filename << '\n';
}
else {
std::wstring s;
std::getline(istrm, s);
std::wcout << s << std::endl;
}
Then I found some solutions for this using the following libraries
#include <locale>
#include <codecvt>
// open file for reading
std::wifstream istrm(filename, std::ios::binary);
istrm.imbue(std::locale(istrm.getloc(), new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
if (!istrm.is_open()) {
std::cout << "failed to open " << filename << '\n';
}
else {
std::wstring s;
std::getline(istrm, s);
std::wcout << s << std::endl;
}
This time it didn't even compile, got the following errors at the std::codecvt_utf16
line:
Error C4996 'std::codecvt_utf16': warning STL4017: std::wbuffer_convert, std::wstring_convert, and the 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 instead. You can define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received this warning.
I would appreciate if someone can provide a solution for this.
Thanks in advance.