How can I get double quotes into a string literal?

154,385

Solution 1

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.

Solution 2

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.

Share:
154,385
kevthanewversi
Author by

kevthanewversi

SOreadytohelp

Updated on July 09, 2022

Comments

  • kevthanewversi
    kevthanewversi almost 2 years

    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?

    • mrDev
      mrDev over 3 years
      Ha, plus 1 for the pun!
  • frans
    frans over 4 years
    well... my_json << R"("value":")" << string_value << R"(")"; or even just R"("value":"value1")" - I hoped there would be something more readable for JSON handling :)
  • pjcard
    pjcard over 3 years
    Yes, clarified further that in that situation, it's not much clearer. (For what it's worth, your sample snippet is incorrect, somewhat proving your point!)