gpt4 book ai didi

c++ - 使用 std::wifstream 读取具有特殊字符的 unicode 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:08 29 4
gpt4 key购买 nike

在Linux环境下,我有一段读取unicode文件的代码,类似下图。

但是,特殊字符(如丹麦字母 æ、ø 和 å)无法正确处理。对于“abcæøåabc”行,输出只是“abc”。使用调试器我可以看到 wline 的内容也只是 a\000b\000c\000

#include <fstream>
#include <string>

std::wifstream wif("myfile.txt");
if (wif.is_open())
{
//set proper position compared to byteorder
wif.seekg(2, std::ios::beg);
std::wstring wline;

while (wif.good())
{
std::getline(wif, wline);
if (!wif.eof())
{
std::wstring convert;
for (auto c : wline)
{
if (c != '\0')
convert += c;
}
}
}
}
wif.close();

谁能告诉我如何读整行?

感谢和问候

最佳答案

您必须使用 imbue()方法告诉 wifstream 该文件编码为 UTF-16,并让它为您使用 BOM。您不必手动通过 BOM seekg()。例如:

#include <fstream>
#include <string>
#include <locale>
#include <codecvt>

// open as a byte stream
std::wifstream wif("myfile.txt", std::ios::binary);
if (wif.is_open())
{
// apply BOM-sensitive UTF-16 facet
wif.imbue(std::locale(wif.getloc(), new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));

std::wstring wline;
while (std::getline(wif, wline))
{
std::wstring convert;
for (auto c : wline)
{
if (c != L'\0')
convert += c;
}
}

wif.close();
}

关于c++ - 使用 std::wifstream 读取具有特殊字符的 unicode 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26121782/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com