views:

3786

answers:

4

Is there any way to have multiline plaintext constant literals in C++, ala Perl? Maybe some parsing trick with #includeing a file? I can't think of one, but boy, that would be nice. I know it'll be in C++0x.

+3  A: 

You can just do this:

const char *text = "This is my string it is"
     "very long";
Eric
and there will be no space between "is" and "very" - you should include a space somewhere. :)
Paulius Maruška
+2  A: 

Just use it like this:

"Start of the string"
"The next line of the string"
"...."

"The last line"

As long as nothing is inbetween those strings it will be concatenated.

EFraim
Nothing but white space. Also it will not be the next line as there is no character specifying where the eol is (you could add \n).
Martin York
+2  A: 
const char * myreply = "I don't really"
                       "understand what"
                       "your problem is.";
Dipstick
"The maybe youshould have asked forclarification in a commentinstead of answering."
Rob Kennedy
+20  A: 

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

The indentation doesn't matter, since it's not inside the quotes.

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:

const char *text2 =
"Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, making it part of the string literal.

unwind
@Martin: I just realixed, fixed. Thanks.
unwind
I have been told in the past that the first option can be up to implementation, however I've yet to find a compiler that doesn't honor that syntax.
Jason Mock