Search code examples
c++unicode

std::wcout printing unicode characters but they are hidden


So, the following code:

#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
#include <codecvt>

int main()
{
    setlocale(LC_ALL, "");

    std::wstring a;
    std::wcout << L"Type a string: " << std::endl;
    std::getline(std::wcin, a);
    std::wcout << a << std::endl;
    getchar();
}

When I type "åäö" I get some weird output. The terminal's cursor is indented, but there is no text behind it. If I use my right arrow key to move the cursor forward the "åäö" reveal themselves as I click the right arrow key.

If I include English letters so that the input is "helloåäö" the output is "hello" but as I click my right arrow key "helloåäö" appears letter by letter.

Why does this happen and more importantly how can I fix it?

Edit: I compile with Visual Studio's compiler on Windows. When I tried this exact code in repl.it (they use clang) it works like a charm. Is the problem caused by my code, Windows or Visual Studio?


Solution

  • Windows requires some OS-specific calls to set up the console for Unicode:

    #include <iostream>
    #include <string>
    #include <io.h>
    #include <fcntl.h>
    
    // From fctrl.h:
    //  #define _O_U16TEXT     0x20000 // file mode is UTF16 no BOM (translated)
    //  #define _O_WTEXT       0x10000 // file mode is UTF16 (translated)
    
    int main()
    {
        _setmode(_fileno(stdout), _O_WTEXT); // or _O_U16TEXT, either work
        _setmode(_fileno(stdin), _O_WTEXT);
    
        std::wstring a;
        std::wcout << L"Type a string: ";
        std::getline(std::wcin, a);
        std::wcout << a << std::endl;
        getwchar();
    }
    

    Output:

    Type a string: helloåäö马克
    helloåäö马克