CS253 Raw Strings
Say that you want your program to write this:
Don't be "afraid" of letters: \a\b\c\d\e\f\g
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
\c
, \d
, \e
, and \g
.
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 …
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 …
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?
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
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!
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.
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!
Modified: 2017-04-24T11:14 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |