Writing the Persian (farsi) class wfstream in the output file

How can I write Persian text, for example "خلیج فارس", in a file using std::wfstream?
I tried the following code but it does not work.

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::wfstream f("D:\\test.txt", std::ios::out);
    std::wstring s1(L"خلیج فارس");
    f << s1.c_str();
    f.close();

    return 0;
}

After starting the program, the file is empty.

+4
source share
2 answers

You can use utf-8 C ++ 11 string literal and standard stream and string:

#include <iostream>
#include <fstream>

int main()
{
    std::fstream f("D:\\test.txt", std::ios::out);
    std::string s1(u8"خلیج فارس");
    f << s1;
    f.close();

    return 0;
}
+5
source

First of all, you can leave

f << s1.c_str();

Just use

f << s1;

To write "خلیج فارس" with std::wstream, you must specify imbuefor the Persian language, for example:

f.imbue(std::locale("fa_IR"));

before writing to a file.

+2
source

Source: https://habr.com/ru/post/1622645/


All Articles