Search code examples
c++utf-8c++17utf-16wstring

Trouble with UTF-8 input


My simple code has no trouble with Japanese characters when outputting, but for some reason it doesn't take input properly, is it lacking something?

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    SetConsoleCP(CP_UTF8);

std::wstring s = L"こんにちは, 世界!\nHello, World!";
std::wcout << s << endl;
std::wstring test;

getline(wcin, test);

std::wstring test2 = test;
std::wcout << test2 << endl;

std::wstring test3 = test2;
std::wcout << test3 << endl;
std::wcout << "Press ENTER to exit.";
std::wcout << "\n";
cin.get();
return 0;
}

Solution

  • This code worked for me in the Windows 10 command prompt.

    #include <fcntl.h>
    #include <io.h>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        _setmode(_fileno(stdout), _O_WTEXT);  // or _O_U16TEXT, either work
        _setmode(_fileno(stdin), _O_WTEXT);
    
        wstring s = L"こんにちは, 世界!\nHello, World!";
        wcout << s << endl;
    
        wstring test;
        getline(wcin, test);
        wcout << test << endl;
        return 0;
    }
    

    Output:

    C:\>test
    こんにちは, 世界!
    Hello, World!
    你好马克!                << input line
    你好马克!