Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get double quotes into a string literal?

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?

like image 613
kevthanewversi Avatar asked Sep 09 '12 11:09

kevthanewversi


People also ask

How do you put quotation marks in a string?

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.

How do you pass a double quote in a string C++?

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.


2 Answers

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.

like image 89
Mark Byers Avatar answered Sep 25 '22 02:09

Mark Byers


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.

like image 29
pjcard Avatar answered Sep 25 '22 02:09

pjcard