diwatu
diwatu

Reputation: 5699

C++ multiline string raw literal

We can define a string with multiline like this:

const char* text1 = "part 1"
                    "part 2"
                    "part 3"
                    "part 4";

const char* text2 = "part 1\
                     part 2\
                     part 3\
                     part 4";

How about with raw literal, I tried all, no one works

std::string text1 = R"part 1"+
                    R"part 2"+ 
                    R"part 3"+
                    R"part 4";

std::string text2 = R"part 1"
                    R"part 2" 
                    R"part 3"
                    R"part 4";

std::string text3 = R"part 1\
                      part 2\ 
                      part 3\
                      part 4";

std::string text4 = R"part 1
                      part 2 
                      part 3
                      part 4";

Upvotes: 28

Views: 58796

Answers (2)

Qaz
Qaz

Reputation: 61920

Just write it as you want it:

std::string text = R"(part 1
part 2
part 3
part 4)";

The other thing you didn't put in was the required pair of parentheses around the entire string.

Also keep in mind any leading spaces on the part 2-4 lines that you might put in to keep the code formatted are included, as well as a leading newline to get part 1 with the others, so it does make it rather ugly to see in the code sometimes.

An option that might be plausible for keeping things tidy, but still using raw string literals is to concatenate newlines:

R"(part 1)" "\n" 
R"(part 2)" "\n" 
R"(part 3)" "\n" 
R"(part 4)"

Upvotes: 45

Michael Burr
Michael Burr

Reputation: 340218

Note that raw string literals are delimited by R"( and )" (or you can add to the delimiter by adding characters between the quote and the parens if you need additional 'uniqueness').

#include <iostream>
#include <ostream>
#include <string>

int main () 
{
    // raw-string literal example with the literal made up of separate, concatenated literals
    std::string s = R"(abc)" 
                    R"( followed by not a newline: \n)"
                    " which is then followed by a non-raw literal that's concatenated \n with"
                    " an embedded non-raw newline";

    std::cout << s << std::endl;

    return 0;
}

Upvotes: 45

Related Questions