unicode“意识” std :: getline [英] unicode "aware" std::getline

查看:463
本文介绍了unicode“意识” std :: getline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在测试如何编写一个C ++应用程序,实际上可以读取(和更改)文本文件,同时尊重用于文本的编码。我希望(对于其他API)显式转换所有读取的文本为UTF-8供内部使用。
独立于文件中的实际编码。

Well I'm testing how to write a C++ application that actually can read (and change) text files while respecting the encoding used for the text. I wish (for other API's) to explicitly convert all read text to UTF-8 for internal use. Independent of what the actual encoding in the file was.

我在Windows上并测试使用ansiUTF-8似乎工作正常)。然后unicode big endian不工作; std :: getline 结果似乎是原始字节数组,没有将文件(UTF-16 ??)转换为UTF-8。

I am on windows and testing a textfile encoded using "ansi" "UTF-8" (those seem to work correctly). And then "unicode big endian" doesn't work; the std::getline result seems to be the raw byte array, no conversion of the file (UTF-16??) to UTF-8.

如何强制这样做?我不知道文件是什么编码的。使用的代码:

How can I force this? I do not know beforehand what the file is encoded with. Code used:

std::string retString;
if (isValidIndex(file_index) && OpenFilestreams()[file_index]->good()) {
    std::getline(*OpenFilestreams()[file_index], retString);
}
return retString;

其中档案 OpenFilestreams() 一个向量(静态包含所有打开的文件)和 file_index 向量中的索引。那么如何确保这里读取的是正确的编码?

Where file is OpenFilestreams() "is" a vector (static one containing all opened files), and file_index an index in the vector. So how to make sure here that it reads using the correct encoding?

至于使用:

实际上尝试使用以下命令将其转换为wstring:

Actually trying to convert it to a wstring using:

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(input.c_str());

提供 std :: range_error 异常。 (我需要wstring其他windows api函数)。

Gives the a std::range_error exception. (I need wstring for other windows api functions).

推荐答案

没有办法std :: getline可以获得编码文件。您可以使用std :: locale来更改所使用的编码。

There is no way that std::getline can get the encoding of the file. You can uses std::locale to change the encoding used.

一些Unicode文件包含BOM(指定使用的编码),不需要。

Some Unicode files contain BOM (which state the encoding used), by this is not required.

通常,如果BOM存在,文本应用程序使用该编码,如果不尝试进行启发式识别所使用的编码,并读取具有该编码的文本,则对文本进行标准化(例如: UTF8),假设在应用程序的其余部分,文本是在UTF8,并保存在读取的相同的编码。

Normally the text applications if the BOM is present use that encoding and if not try to make heuristics for identify the encoding used and read the text with that encoding, normalize the text (ex: UTF8), assume in the rest of the app the text is in UTF8, and saved in the same encoding that was read.

有关Unicode的一些信息 Joel Spolsky Unicode文章

其他文章关于在C ++中阅读Unicode编码

Some info about Unicode Joel Spolsky Unicode Article
Other Article about Reading Unicode Encodings in C++

这篇关于unicode“意识” std :: getline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆