tags:

views:

211

answers:

3

How do you say something like this?

static const string message = "This is a message.\n
                               It continues in the next line"

The problem is, the next line isn't being recognized as part of the string..

How to fix that? Or is the only solution to create an array of strings and then initialize the array to hold each line?

+16  A: 

Enclose each line in its own set of quotes:

static const string message = "This is a message.\n"
                              "It continues in the next line";

The compiler will combine them into a single string.

RichieHindle
More accurately, the preprocessor will.
ephemient
@ephemient: actually, no the preprocessor is not the layer that does this. You can test this for yourself by making a small app and compiling with "gcc -E test.c". That will output the result of the preprocessor. You will find that the strings are still separate. It is the compiler itself which does the concatenation of adjacent string constant *not* the preprocessor.
Evan Teran
@ephemient: in fact, the C99 standard has a note in the section regarding the preprocessor: "148) Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 5.1.1.2); thus, an expansion that results in two string literals is an invalid directive."
Evan Teran
Hmm, in my experience, some `cpp` implementations will merge strings... I guess they're out of spec.
ephemient
+9  A: 

You can use a trailing slash or quote each line, thus

"This is a message.\n \
 It continues in the next line"

or

"This is a message."
"It continues in the next line"
disown
I always used to use the first form but had problems with inserted white space from indenting... ie if that statement was singly indented with 4 spaces there would be four extra spaces in the middle of the string. Now I use the second form exclusively.
Jamie Cook
+1  A: 

In C++ as in C, string litterals separated by whitespace are implicitly concatenated, so

"foo" "bar"

is equivalent to:

"foobar"

So you want:

static const string message = "This is a message.\n"
                               "It continues in the next line";
anon