使用类 wfstream 在输出文件中编写波斯语(Farsi)

5
我应该如何使用std::wfstream将波斯文(如“خلیج فارس”)写入文件?我尝试了以下代码,但没有成功。
#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;
}

运行程序后,文件为空。

我检查了输出文件,它是空的。 - SaeidMo7
1
如果波斯语是您的默认系统语言环境,请执行以下操作:f.imbue(std::locale("")); - John_West
它必须是std::wfstream吗?还是std::fstream也可以? - robsn
@robsn:是的,因为它在ios_base中声明了。 - Mykola
请指定您的平台 - Windows、Linux、Mac?在某些操作系统上,控制台是Unicode友好的,在某些操作系统上则不太友好。 - Seva Alekseyev
2个回答

5
您可以使用C++11的utf-8字符串字面量以及标准的fstream和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;
}

3

首先,您可以向左移动

f << s1.c_str();

只需使用

f << s1;

为了使用std::wstream编写“خلیج فارس”,您必须像这样指定波斯语区域设置的imbue
f.imbue(std::locale("fa_IR"));

在你写入文件之前。


抱歉,我认为应该是 fa_IR(http://stdcxx.apache.org/doc/stdlibref/locale.html)。 - John_West
@John_West:我不太了解东方语言。 - Mykola
@John_West:感谢您的回复! - Mykola

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接