C++ 11:普通字符串文字和UTF-8字符串文字之间的区别示例?

标签 c++ utf-8 character-encoding c++11 string-literals

A string literal that does not begin with an encoding-prefix is an ordinary string literal, and is initialized with the given characters.

A string literal that begins with u8, such as u8"asdf", is a UTF-8 string literal and is initialized with the given characters as encoded in UTF-8.

我不明白普通字符串文字和 UTF-8 字符串文字之间的区别。

有人可以提供他们不同的情况的例子吗? (导致不同的编译器输出)

(我的意思是从标准的 POV,而不是任何特定的实现)

Each source character set member in a character literal or a string literal, as well as each escape sequence and universal-character-name in a character literal or a non-raw string literal, is converted to the corresponding member of the execution character set.

最佳答案

C 和 C++ 语言在它们的实现中有很大的自由度。在 UTF-8 成为“以单字节编码文本的方式”之前很久就编写了 C:不同的系统具有不同的文本编码。

所以在 C 和 C++ 中字符串的字节值是多少实际上取决于编译器。 'A' 是编译器为字符 A 选择的任何编码,它可能与 UTF-8 不一致。

C++ 增加了编译器必须支持真正的 UTF-8 字符串文字的要求。 u8"A"[0] 的位值由 C++ 标准通过 UTF-8 标准固定,无论编译器的目标平台的首选编码如何。

现在,就像大多数平台 C++ 目标使用 2 的补码整数一样,大多数编译器的字符编码大多与 UTF-8 兼容。因此对于像 "hello world" 这样的字符串,u8"hello world" 几乎肯定是相同的。

具体例子,来自man gcc

-fexec-charset=charset

Set the execution character set, used for string and character constants. The default is UTF-8. charset can be any encoding supported by the system's iconv library routine.

-finput-charset=charset

Set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default is UTF-8. This can be overridden by either the locale or this command line option. Currently the command line option takes precedence if there's a conflict. charset can be any encoding supported by the system's iconv library routine.

是一个可以改变C/C++的执行和输入字符集的例子。

关于C++ 11:普通字符串文字和UTF-8字符串文字之间的区别示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14679717/

相关文章:

c++ - 等待按钮按下(QT)

c++ - 为什么我不能在特定进程的范围内使用 MPI_Scatter()?

python - 未知编码 : idna in Python Requests

C中putchar的字符集

php - 获取带有汉字的PHP源码

c++ - 从 C/C++ 中的周数计算公历日期

c++ - 如何实现具有循环引用的对象的深拷贝或克隆?

php - UTF-8贯穿始终

csv - 将 csv 文件从 s3 复制到 redshift 时出现问题

google-chrome - 这个 INSANE 空间字符是什么??? (谷歌浏览器)