CS253: Software Development with C++

Fall 2018

String Literals

See this page as a slide show

CS253 String Literals

made at imgflip.com

Literals

String Literals

A "string literal" is an anonymous array of constant characters. These are equivalent:

cout << "FN-2187";
FN-2187
const char whatever[] = "FN-2187";
cout << whatever;
FN-2187
const char whatever[] = "FN-2187";
const char *p = &whatever[0];
cout << p;
FN-2187

Escape Sequences:

SequenceMeaningSequenceMeaning
\abell\''
\bbackspace\""
\fform feed\\\
\nnewline\0ddd0–3 octal digits
\rcarriage return\xdd1–∞ hex digits
\thorizontal tab\uddddUnicode U+dddd
\vvertical tab\UddddddddUnicode U+dddddddd

String Pasting

Two adjacent string literals are merged into one at compile-time:

cout << "alpha beta "  "gamma delta "
        "epsilon\n";
alpha beta gamma delta epsilon
cout << "Business plan:\n\n"
        "1. Collect underpants\n"
        "2. ?\n"
        "3. Profit\n";
Business plan:

1. Collect underpants
2. ?
3. Profit

Raw Strings

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 << "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

A raw string starts with:

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

and ends with:

)the-same-up-to-sixteen-chars"
cout << R"X(A goatee!  :-)"  Cool!)X";
A goatee!  :-)"  Cool!
cout << R"WashYourHair(What the #"%'&*)?)WashYourHair";
What the #"%'&*)?
cout << R"(The degenerate case)";
The degenerate case

Comparing C-Style Strings

if ("foo" < "bar")
    cout << "😢";
c.cc:1: warning: comparison with string literal results in unspecified behavior
😢

Comparing C-style strings properly.

Comparing C++ std::strings

    <  >  <=  >=  ==  !=

Example

string name = "Conan O’Brien";
if (name == "Conan O’Brien")
    cout << "good 1\n";
if (name < "Zulu")
    cout << "good 2\n";
if (name > "Andy Richter")
    cout << "good 3\n";
if (name == name)
    cout << "good 4\n";
good 1
good 2
good 3
good 4

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-07-13T00:12

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