c++ - 在 C++ 中用 '$' 编写原始字符串的正确格式是什么?

标签 c++ string

我正在从 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-char

d-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/

相关文章:

c++ - 主线程的 Firebreath 计时器回调

c++ - 微 Controller - 按钮 'holding down' 监听器

python - 旧的 python 散列从左到右完成——为什么不好?

python - python中的正则表达式搜索

c++ - 如果没有 if,std::count_if 会更快吗?

c++ - 如何在该程序中将if else语句转换为switch语句? Visual Studio 2019 C++

C++ 多组可变函数参数

java - 如何从这样的字符串中提取 double

javascript - Js 如何获取字符串中的数字之和?

linq - LINQ .distinct 方法如何排序?