Answer the question
In order to leave comments, you need to log in
How to read C++ Unicode file with Russian text?
Hello everyone) There was a task to read Unicode files with content in Russian. To solve the problem, I created a test file in Notepad, filled it with Russian text and saved it as Unicode. After I tried to read it in the following ways:
1)
std::wstring readUtf16(const std::string &filename) {
std::ifstream file(filename.c_str());
std::stringstream ss;
ss << file.rdbuf() << '\0';
return std::wstring((wchar_t*)ss.str().c_str());
}
std::wstring ws = readUtf16("test.txt");
std::string s(ws.begin(),ws.end());
std::cout << s.size() << " "<< s;
const std::locale utf16_locale_in = std::locale(std::locale::empty(),
new std::codecvt_utf8_utf16<wchar_t>());
{
std::wifstream input("test.txt");
std::wstring ws;
input.imbue(utf16_locale_in);
std::getline(input,ws);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> converter;
std::string s = converter.to_bytes(ws);
std::cout << s << " " << s.size();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question