Elton Stålspets
Elton Stålspets

Reputation: 55

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?

Upvotes: 3

Views: 1216

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177406

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åäö马克

Upvotes: 5

Related Questions