Morteza Rahimzade
Morteza Rahimzade

Reputation: 39

Farsi character utf8 in c++

i m trying to read and write Farsi characters in c++ and i want to show them in CMD first thing i fix is Font i add Farsi Character to that and now i can write on the screen for example ب (uni : $0628) with this code:

#include <iostream>
#include <io.h>
#include <fcntl.h>
using namespace std;
int main() {
    _setmode(_fileno(stdout), _O_U16TEXT);
    wcout << L"\u0628 \n";
    wcout << L"ب"<<endl;
    system("pause");
} 

but how i can keep this character ... for Latin characters we can use char or string but how about Farsi character utf8 ?!

and how i can get them ... for Latin characters we use cin>>or gets_s

should i use wchar_t? if yes how? because with this code it show wrong character ...

wchar_t a='\u0628';
wcout <<a;

and i can't show this character بـ (uni $FE91) even though that exist in my installed font but ب (uni $0628) showed correctly

thanks in advance

Upvotes: 3

Views: 1233

Answers (1)

YePhIcK
YePhIcK

Reputation: 5856

The solution is the following line:

wchar_t a=L'\u0628';

The use of L tells the compiler that your type char is a wide char ("large" type, I guess? At least that's how I remember it) and this makes sure the value doesn't get truncated to 8 bits - thus this works as intended.

UPDATE

If you are building/running this as a console application in Windows you need to manage your code pages accordingly. The following code worked for me when using Cyrillic input (Windows code page 1251) when I set the proper code page before wcin and cout calls, basically at the very top of my main():

SetConsoleOutputCP(1251);
SetConsoleCP(1251);

For Farsi I'd expect you should use code page 1256.


Full test code for your reference:

#include <iostream>
#include <Windows.h>

using namespace std;

void main()
{
    SetConsoleOutputCP(1256); // to manage console output
    SetConsoleCP(1256);       // to properly process console input

    wchar_t b;
    wcin >> b;
    wcout << b << endl;
}

Upvotes: 2

Related Questions