Search code examples
c++string-literals

Is it possible to insert escape sequence in a raw string literal?


What if I want this to consume fewer lines in my file?

auto rsl = R"rsl(==== WELCOME ===

Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Pellentesque sed scelerisque purus. Nulla facilisi. 
Suspendisse laoreet mattis urna sit amet suscipit.

===== Thanks for your attention ====)rsl";

Can I sprinkle this raw string literal with escaped characters like:

auto rsl = R"rsl(==== WELCOME ===\n
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Pellentesque sed scelerisque purus. Nulla facilisi. 
Suspendisse laoreet mattis urna sit amet suscipit.\n
===== Thanks for your attention ====)rsl";

Or even better case, what if I have to lazily copy-paste some encoded utf-8 literal into raw string literal like this:

auto u8 = u8"UTF-8 encoded string literal: \u041F\u0420\u0418\u0412\u0415\u0422 \n";
auto u8Rs = u8R"u8R(UTF-8 encoded string literal: \u041F\u0420\u0418\u0412\u0415\u0422
some additional stuff I want to add 
to the previous string literal
because requirements slightly changed
or something)u8R";

Because the output will be wildly different in those cases


Solution

  • While it's usually best to stick to one type of literal or the other, you can mix raw and non-raw literals in concatenation:

    auto u8 = u8"UTF-8 encoded string literal: \u041F\u0420\u0418\u0412\u0415\u0422 \n";
    auto u8Rs = u8R"u8R(UTF-8 encoded string literal: )u8R" u8"\u041F\u0420\u0418\u0412\u0415\u0422" u8R"u8R(
    some additional stuff I want to add 
    to the previous string literal
    because requirements slightly changed
    or something)u8R";
    

    Yes, it's ugly. I would seriously consider whether it's uglier than the alternative of a single non-raw literal. In the case of saving vertical editor space, I'd say don't. Use the raw literal and let people assume that what they see is exactly what they get rather than hiding extra newlines.