我正在从 cplusplus.com tutorial on constants 中学习 C++ 中的原始字符串.根据该站点上的定义,原始字符串应以 R"sequence(
开头。并以 )sequence
结尾哪里sequence
可以是任何字符序列。
该网站的示例之一如下:R"&%$(string with \backslash)&%$"
但是,当我尝试编译包含上述原始字符串的代码时,出现编译错误。
test.cpp:5:28: error: invalid character '$' in raw string delimiter
5 | std::string str = R"&%$(string with \backslash)&%$";
| ^
test.cpp:5:23: error: stray 'R' in program
我在 Windows 和 Linux 上使用 g++ 和 clang++ 进行了尝试。他们都没有工作。
最佳答案
来自 C++ reference :
delimiter: A character sequence made of any source character but parentheses, backslash and spaces (can be empty, and at most 16 characters long)
请注意此处的“任何源字符”部分。
让我们看看标准是怎么说的:
来自 [gram.lex]:
raw-string:
"d-char-sequenceopt(r-char-sequenceopt)d-char-sequenceopt"...
d-char-sequence:
d-char
d-char-sequence d-chard-char:
any member of the basic source character set except: space, the left parenthesis(
, the right parenthesis)
, the backslash\
, and the control characters representing horizontal tab, vertical tab, form feed, and newline.
那么,基本的源字符集是什么?来自 [lex.charset]:
The basic source character set consists of 96 characters: the space character, the control characters representing horizontal tab, vertical tab, form feed, and new-line, plus the following 91 graphical characters:
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9_ { } [ ] # ( ) < > % : ; . ? * + - / ^ & |~! = , \ " ’
... 不包括
$
;所以结论是美元符号$
不能是分隔符序列的一部分。
关于c++ - 在 C++ 中用 '$' 编写原始字符串的正确格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66401190/