CS253: Software Development with C++

Spring 2018

Raw Strings

See this page as a slide show

CS253 Raw Strings

Quoting

Say that you want your program to write this:

    Don't be "afraid" of letters:
    \a\b\c\d\e\f\g

Attempt #1

You might try this:

cout << "Don't be "afraid" of letters:\n\a\b\c\d\e\f\g";
c.cc:1: warning: unknown escape sequence: '\c'
c.cc:1: warning: unknown escape sequence: '\d'
c.cc:1: warning: non-ISO-standard escape sequence, '\e'
c.cc:1: warning: unknown escape sequence: '\g'
c.cc:1: error: unable to find string literal operator 'operator""afraid' with 
   'const char [30]', 'long unsigned int' arguments

Attempt #2

Oh, that’s right—we have to escape special characters, and backslash is a special character:

cout << "Don\'t be \"afraid\" of letters\:\\n\\a\\b\\c\\d\\e\\f\\g";
c.cc:1: warning: unknown escape sequence: '\:'
Don't be "afraid" of letters:\n\a\b\c\d\e\f\g

Better …

Attempt #3

We can’t just blindly escape all special characters; the colon doesn’t need escaping.

cout << "Don\'t be \"afraid\" of letters:\\n\\a\\b\\c\\d\\e\\f\\g";
Don't be "afraid" of letters:\n\a\b\c\d\e\f\g

Better …

Attempt #4

Oh, that’s right—the \n is supposed to be a newline.

cout << "Don\'t be \"afraid\" of letters:\n\\a\\b\\c\\d\\e\\f\\g";
Don't be "afraid" of letters:
\a\b\c\d\e\f\g

Any other problems?

Attempt #5

It’s not really necessary to escape the apostrophe.

cout << "Don't be \"afraid\" of letters:\n\\a\\b\\c\\d\\e\\f\\g";
Don't be "afraid" of letters:
\a\b\c\d\e\f\g

Raw Strings

A raw string starts with R"( and ends with )". The parens are not part of the string.

cout << R"(Don't be "afraid" of letters:
\a\b\c\d\e\f\g)";
Don't be "afraid" of letters:
\a\b\c\d\e\f\g

Cool! Quotes inside of quotes!

However …

What if the string contains a right paren? I want to emit:

    A goatee!  :-)"  Cool!
cout << R"(A goatee!  :-)"  Cool!)";
c.cc:1: warning: missing terminating " character
c.cc:1: error: missing terminating " character

That didn’t work. The )" at the bottom of the face was taken to be the end of the raw string.

Solution

I lied. Really, a raw string starts with:

R"whatever-you-like-up-to-sixteen-chars(

and ends with:

)the-same-sixteen-chars"
cout << R"X(A goatee!  :-)"  Cool!)X";
A goatee!  :-)"  Cool!
cout << R"0123456789abcdef(A goatee!  :-)"  Cool!)0123456789abcdef";
A goatee!  :-)"  Cool!

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building