user12317345
user12317345

Reputation:

How to get non-latin input in console

I wanted to get Latin and also non-Latin characters as input but there is a problem here. When I am going to enter Persian words like (آزمایشی), in the console just I get ?????. How can I fix this issue in which I can get nonlatin input and save them in the wchar_t data type? I have used the following API to change the code page of the console, but it doesn't work.

void SetConsoleToUnicodeFont()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    if (IsWindowsVistaOrGreater())
    {
        // Call the documented function.
        typedef BOOL(WINAPI* pfSetCurrentConsoleFontEx)(HANDLE, BOOL, PCONSOLE_FONT_INFOEX);
        HMODULE hMod = GetModuleHandle(TEXT("kernel32.dll"));
        pfSetCurrentConsoleFontEx pfSCCFX = (pfSetCurrentConsoleFontEx)GetProcAddress(hMod, "SetCurrentConsoleFontEx");

        CONSOLE_FONT_INFOEX cfix;
        cfix.cbSize = sizeof(cfix);
        cfix.nFont = 12;
        cfix.dwFontSize.X = 8;
        cfix.dwFontSize.Y = 14;
        cfix.FontFamily = FF_DONTCARE;
        cfix.FontWeight = 400;  // normal weight
        lstrcpyW(cfix.FaceName, L"Lucida Console");

        pfSCCFX(hConsole,
            FALSE, /* set font for current window size */
            &cfix);
    }
    else
    {
        // There is no supported function on these older versions,
        // so we have to call the undocumented one.
        typedef BOOL(WINAPI* pfSetConsoleFont)(HANDLE, DWORD);
        HMODULE hMod = GetModuleHandle(TEXT("kernel32.dll"));
        pfSetConsoleFont pfSCF = (pfSetConsoleFont)GetProcAddress(hMod, "SetConsoleFont");
        pfSCF(hConsole, 12);
    }
}

Upvotes: 0

Views: 156

Answers (1)

Zeus
Zeus

Reputation: 3880

First make sure that your code encoding rule is UTF-8 with signature.

Then you need to modify the code page according to the text you output. For Farsi I'd expect you should use code page 1256.

Finally, modify the translation mode with _setmode (make sure the version is higher than C++11).

Here is the sample:

#include <string>
#include <iostream>
#include <Windows.h>
#include <cstdio>
#include <io.h>
#include <fcntl.h>
using namespace std;
int main() {
     SetConsoleOutputCP(1256);
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wcout << L"wordsزمایشی" << std::endl;
}

Output: enter image description here

Upvotes: 1

Related Questions