gpt4 book ai didi

c++ - 为什么 C++ 中的宽文件流默认会缩小写入数据的范围?

转载 作者:IT老高 更新时间:2023-10-28 22:02:33 24 4
gpt4 key购买 nike

老实说,我只是没有在 C++ 标准库中得到以下设计决策。将宽字符写入文件时,wofstreamwchar_t 转换为 char 字符:

#include <fstream>
#include <string>

int main()
{
using namespace std;

wstring someString = L"Hello StackOverflow!";
wofstream file(L"Test.txt");

file << someString; // the output file will consist of ASCII characters!
}

我知道这与标准 codecvt 有关。 Boost 中有 utf8codecvt .此外,Martin York here on SO 还为 utf16 提供了一个 codecvt .问题是为什么 standard codecvt 会转换宽字符?为什么不按原样写字符!

另外,我们是要使用 C++0x 获得真正的 unicode 流 还是我在这里遗漏了什么?

最佳答案

第一个问题的一个非常部分的答案:文件一个字节序列,所以在处理 wchar_t 时的,wchar_t 之间至少有一些转换和 char必须发生。进行这种“智能”转换需要了解字符编码,因此这就是允许这种转换依赖于语言环境的原因,通过在流的语言环境中使用一个方面。

然后,问题是如何在标准要求的唯一语言环境中进行转换:“经典”语言。对此没有“正确”的答案,因此标准对此非常模糊。我从您的问题中了解到,您认为在 wchar_t[] 和 char[] 之间盲目地强制转换(或 memcpy()-ing)是一个好方法。这不是不合理的,实际上是(或至少是)在某些实现中所做的。

另一个 POV 是,因为 codecvt 是一个语言环境方面,所以可以合理地预期转换是使用“语言环境的编码”进行的(我在这里是手动的,因为这个概念很模糊)。例如,人们会期望土耳其语语言环境使用 ISO-8859-9,或者日语语言环境使用 Shift JIS。通过相似性,“经典”语言环境将转换为此“语言环境的编码”。显然,微软选择了简单的修剪(如果我们假设 wchar_t 代表 UTF-16 并且我们停留在基本的多语言平面,这将导致 IS-8859-1),而我所知道的 Linux 实现决定坚持使用 ASCII。

第二个问题:

Also, are we gonna get real unicode streams with C++0x or am I missing something here?

在 n2857(我手头最新的 C++0x 草案)的 [locale.codecvt] 部分,可以阅读:

The specialization codecvt<char16_t, char, mbstate_t> converts between the UTF-16 and UTF-8 encodings schemes, and the specialization codecvt <char32_t, char, mbstate_t> converts between the UTF-32 and UTF-8 encodings schemes. codecvt<wchar_t,char,mbstate_t> converts between the native character sets for narrow and wide characters.

在 [locale.stdcvt] 部分,我们发现:

For the facet codecvt_utf8: — The facet shall convert between UTF-8 multibyte sequences and UCS2 or UCS4 (depending on the size of Elem) within the program. [...]

For the facet codecvt_utf16: — The facet shall convert between UTF-16 multibyte sequences and UCS2 or UCS4 (depending on the size of Elem) within the program. [...]

For the facet codecvt_utf8_utf16: — The facet shall convert between UTF-8 multibyte sequences and UTF-16 (one or two 16-bit codes) within the program.

所以我猜这意味着"is",但您必须更准确地了解“真正的 unicode 流”是什么意思。

关于c++ - 为什么 C++ 中的宽文件流默认会缩小写入数据的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1509277/

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