When writing a character string of the UTF-8 encoding in wstring each character from the encoding is written in two characters (in the example, the length of the string is 12 instead of 6), because of this it is impossible to display a specific character. Code example

 #include <iostream> using namespace std; int main() { wstring str; getline(wcin, str); wcout << str << ' ' << str[0] << ' ' << str.length() << endl; } 

When you enter a string, Привет displays

Hi 12

When adding localization (code below), it stops accepting Russian letters and leaves the string empty.

 #include <iostream> using namespace std; int main() { //ios_base::sync_with_stdio(false); setlocale(LC_CTYPE, "ru_RU.UTF-8"); wcin.imbue(locale("ru_RU.UTF-8")); wcout.imbue(locale("ru_RU.UTF-8")); wstring str; getline(wcin, str); wcout << str << ' ' << str[0] << ' ' << str.length() << endl; } 

Disabling syncing iostreams with stdio does not help

PS I use in CLion on OS X 10.10.5

PSS using wchar_t* and printf/scanf do not have such problems

    1 answer 1

    Try std::string as source, and then convert:

     std::wstring to_wstr(const std::string& _str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; return converter.from_bytes(_str.c_str()); }