【问题标题】:Unicode characters aren't loading properly from fileUnicode 字符未从文件中正确加载
【发布时间】:2013-11-02 01:12:33
【问题描述】:

我有一个文本文件,其中包含一些字符,包括一些 unicode 字符。我尝试使用以下编码保存此文件但未解决问题:UTF8、不带 BOM 的 UTF8、UCS2 BE 和 UCS2 LE。这是尝试逐行读取文件的代码。

    std::wifstream infile("my_file.txt");
    wchar_t line[1024];
    while (infile.getline(line, sizeof(line))) { ... }

"line" 有一个垃圾值代替 unicode 和 normal 那里有一个 ASCII 字符。它的值看起来像:L"Normal text here" 而不是 L"€Normal text here"

我尝试过其他变体,例如:

    std::wifstream infile("my_file.txt");
    std::wstring line;
    while (std::getline(infile, line)){ ... }

我也尝试过设置语言环境。我在 Windows 电脑上。如何让 unicode 按需要工作?我更喜欢一种适用于所有平台的格式,但在这个阶段我会接受任何东西。

谢谢。

【问题讨论】:

标签: c++ c unicode


【解决方案1】:

您似乎需要为输入流注入语言环境:请参阅https://stackoverflow.com/a/1275260/1967396

typedef wchar_t ucs4_t;

std::locale old_locale;
std::locale utf8_locale(old_locale,new utf8_codecvt_facet<ucs4_t>);

...

std::wifstream input_file("data.utf8");
input_file.imbue(utf8_locale);
ucs4_t item = 0;
while (ifs >> item) { ... }

【讨论】:

    【解决方案2】:

    示例数据包含预期的 Unicode 字符

    提供的样本数据“Normal text here”是 3 字节的 Byte-order-mark (BOM),表示此和以下是 UTF-8 编码文本“Normal text here”。所以各种打开文件的方法都不会得到“€Normal text here”。

    OP 需要创建包含所需“€Normal text here”的文件。

    Windows 为fopen() 中的模式提供非标准选项,例如fopen("file.txt", "rccs=UNICODE")

    http://msdn.microsoft.com/en-us/library/yeby3zcb(v=vs.90).aspx

    一旦文件包含“€”,甚至fopen("file.txt", "r") 也可能会起作用。

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 2012-08-08
      • 2023-04-03
      • 2012-05-17
      • 2020-04-07
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多