只是对系统在处理字符串存储(如果它关心)和打印时使用的编码感到好奇。
问题 1:如果我在 std::string 中存储一个字节的字符串或在 std::wstring 中存储两个字节的字符串,底层整数值是否会根据当前使用的编码而有所不同? (我记得Bjarne说encoding是char和integer(s)之间的映射,所以char应该作为integer(s)存储在内存中,不同的encoding不一定有相同的映射)
问题 2:如果是肯定的,std::string 和 std::wstring 必须知道编码本身(尽管另一个人告诉我这不是真的)?否则,它如何将 char 转换为正确的整数并存储它们?系统如何知道编码?
问题3:在一个特定的系统中默认的编码是什么,如何改变它(是不是所谓的“locale”)?我想同样的机制很重要?
问题4:如果我用std::cout打印一个字符串到屏幕上,是不是相同的编码呢?
最佳答案
(I remember that Bjarne says that encoding is the mapping between char and integer(s) so char should be stored as integer(s) in memory)
不完全是。确保您了解一个重要的区别。
- 字符是文本的最小单位。字母、数字、标点符号、符号、空格等。
- 字节是内存的最小单位。在绝大多数计算机上,这是 8 位。
编码 将字符序列转换为字节序列。 解码是将字节序列转换为字符序列。
令 C 和 C++ 程序员感到困惑的是 char
表示字节,而不是字符! 字节类型的名称 char
是一个前 Unicode 时代的遗产,当时每个人(东亚人除外)都使用单字节编码。但是现在,我们有了 Unicode,它的编码方案每个字符最多有 4 个字节。
Question 1: If I store one-byte string in std::string or two-byte string in std::wstring, will the underlying integer value depend on the encoding currently in use?
是的,会的。假设你有 std::string euro = "€";
那么:
- 与 windows-1252编码,字符串将被编码为字节0x80。
- 与 ISO-8859-15 encoding ,字符串将被编码为字节 0xA4。
- 与 UTF-8编码,字符串将被编码为三个字节0xE2、0x82、0xAC。
Question 3: What is the default encoding in one particular system, and how to change it(Is it so-called "locale")?
取决于平台。在 Unix 上,编码可以指定为 LANG
环境变量的一部分。
~$ echo $LANG
en_US.utf8
Windows 有一个 GetACP
获取“ANSI”代码页码的函数。
Question 4: What if I print a string to the screen with std::cout, is it the same encoding?
不一定。在 Windows 上,命令行使用“OEM”代码页,这通常与别处使用的“ANSI”代码页不同。
关于c++ - 什么时候编码真的很重要? (例如,字符串存储、打印?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4059157/