C++ 如何将双引号放入字符串文字中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12338818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:11:21  来源:igfitidea点击:

How can I get double quotes into a string literal?

c++cstringescapingstring-literals

提问by kevthanewversi

I have the following output created using a printf()statement:

我使用printf()语句创建了以下输出:

printf("She said time flies like an arrow, but fruit flies like a banana.");

but I want to put the actual quotation in double-quotes, so the output is

但我想把实际的引用放在双引号中,所以输出是

She said "time flies like an arrow, but fruit flies like a banana".

她说:“时光如箭,果蝇如香蕉”。

without interfering with the double quotes used to wrap the string literal in the printf()statement.

不干扰用于在printf()语句中包装字符串文字的双引号。

How can I do this?

我怎样才能做到这一点?

回答by Mark Byers

Escape the quotes with backslashes:

用反斜杠转义引号:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape charactersthat you can use in string literals, and these are denoted with a leading backslash.

您可以在字符串文字中使用特殊的转义字符,这些字符用前导反斜杠表示。

回答by pjcard

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

值得庆幸的是,在 C++11 中,还有使用原始字符串文字的更令人愉悦的方法。

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

变成:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

关于在开始引号之后和结束引号之前添加括号,请注意它们几乎可以是最多 16 个字符的任意组合,有助于避免组合出现在字符串本身中的情况。具体来说:

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" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

基本源字符集的任何成员,除了:空格、左括号(、右括号)、反斜杠 \ 和代表水平制表符、垂直制表符、换页和换行符的控制字符”(N3936 §2.14.5 [ lex.string] 语法)和“最多 16 个字符”(第 2.14.5/2 节)

How much clearer it makes this trivial sentence might be debatable, but when used on formatted strings like HTML or JSON, it's unquestionably far clearer.

它使这个微不足道的句子清晰到什么程度可能是有争议的,但是当用于 HTML 或 JSON 等格式化字符串时,它无疑要清晰得多。