I have the following output created using a printf()
statement:
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.
How can I do this?
Within a character string, to represent a single quotation mark or apostrophe, use two single quotation marks. (In other words, a single quotation mark is the escape character for a single quotation mark.) A double quotation mark does not need an escape character.
To have a double quote as a character in a string literal, do something like, char ident[] = "ab"cd"; The backslash is used in an escape sequence, to avoid conflict with delimiters. To have a double quote as a character, there is no need for the backslash: '”' is alright.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
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:
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)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With