I'm in need of reading both UTF-8 string (std::string
) and UTF-16 string (std::u16string
) from a file (opened with ifstream
).
The UTF-8 string is easy, I think I can just use something like std::getline(stream, str, '\0')
.
But about UTF-16, I'm not sure how I can actually read it. I know I can maybe loop in the file and read 2 bytes each time until a 0x0000
byte, but I'm not sure if that is the right and best way to do it.
So, how can I read it?
-- edit --
For now, I'm doing it this way, is this ok?
std::string binaryReader::ru16str_n()
{
std::u16string str;
char16_t ch = 0;
while (true)
{
binary.read(reinterpret_cast<char*>(&ch), 2);
if (ch != '\0')
str.push_back(ch);
else break;
}
return std::wstring_convert<
std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(str);
}