0

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?

  • This looks like an issue in Windows console. Once you press any key, your program exits, so appearing letter by letter is not a case of the program. Try to run your program in Windows Terminal or Power Shell, does the issue still exist there? – 273K Jan 20 '21 at 14:01
  • Try also `std::wcout << a << std::endl;`. – 273K Jan 20 '21 at 14:03
  • Does this answer your question? [How do I print UTF-8 from c++ console application on Windows](https://stackoverflow.com/questions/1371012/how-do-i-print-utf-8-from-c-console-application-on-windows) – JosefZ Jan 20 '21 at 16:31
  • @S.M. I added the ´std::endl´, I ran it in PowerShell and I compiled it with MinGW but with the same result every time. At this point, I'm pretty sure it is something with the code. – Elton Stålspets Jan 20 '21 at 19:34
  • Relevant: https://stackoverflow.com/a/64000948/235698 – Mark Tolonen Jan 20 '21 at 19:41

1 Answers1

1

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

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

int main()
{
    _setmode(_fileno(stdout),  _O_U16TEXT);
    _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åäö马克

Mark Tolonen
  • 148,243
  • 22
  • 160
  • 229