我如何在c++中使用unicode u003c

How can I use unicode u003c in C++?

本文关键字:unicode u003c c++      更新时间:2023-10-16

我想在c++中像这样使用unicode u003c。

const static string strUnicode = "u003c";

但是在编译时出现了错误。

error: u003c is not a valid universal character

我发现在u0001和u009f之间的unicode字符会导致相同的编译错误。是bug吗?我如何在c++中正确使用这些unicode字符?

在c++ 11之前,c++不允许在0xA0下有代码点的Unicode转义,除了0x24 ($), 0x40(@)和0x60(')。

在c++ 11中,这个限制被取消了,它允许整个UCS范围(0x0-0x10FFFF),除了代理代码点(0xD800-0xDFFF)。

C仍然有与c++ 98相同的限制。

参考:https://en.cppreference.com/w/cpp/language/escape(参见"通用字符名称的范围";部分)。

(根据interjay的评论编辑):

对于c++,它应该工作,只要使用的编译器和使用的标准(例如-std=c++11 for g++)足够新。

对于C,没有解决方案,这是注定的;)

例如,如果我希望在UTF16格式的代码中插入一些俄语文本(根据平台的不同,这将是UTF-16LE或UTF-16BE),我不能这样写:

uint16_t ustr[]= u"u043fu0435u0434u0438u0438u0020u2014u0020";

:

uint16_t ustr[]= {0x043f,0x0435,0x0434,0x0438,0x0438,0x0020,0x2014,0x0020,0};

代理对也不工作:

uint16_t usp[] = u"ud83cudf54"; /* surrogate pair */
编辑:这可能很难相信,但是gcc-5.4在这个代码片段上给出了错误(是的,它一定是在预处理期间发生的,是的,它在#if 0#endif之间):
#if 0
Some u sequences give errors like these:
error: u0020 is not a valid universal character
error: ud83c is not a valid universal character
error: udf54 is not a valid universal character
#endif

编辑:重现问题的最简单程序:

int main (void) { u"u0020"; return 0; }

结果:

gcc (ver-5.4, -std=c11):     error: u0020 is not a valid universal character
gcc (ver-10.2, -std=c11):    error: u0020 is not a valid universal character
clang (ver-3.4.2, -std=c11): error: character ' ' cannot be specified by a universal character name