553

Is there any way to have multi-line plain-text, constant literals in C++, à la Perl? Maybe some parsing trick with #includeing a file?

I know you can do it with raw strings in C++11.

3
  • 1
    Generally you don't want to embed string literals into code. For I18N and L10N it is preferable to put string literals into a configuration file that is loaded at run time. Jul 16, 2009 at 7:09
  • 58
    There are enough cases where putting string literals into code is not a problem: if the string isn't used to represent it to the user; i.e.: SQL statements, file names, registry key names,command lines to be executed, ...
    – mmmmmmmm
    Jul 16, 2009 at 7:18
  • 3
    @Martin: It can still be useful to know, however. I've done it to break up complex regexs, for example.
    – Boojum
    Jul 16, 2009 at 7:22

10 Answers 10

746

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, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

8
  • 3
    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
    Oct 22, 2010 at 18:48
  • 35
    @Jason: it was not necessarily a part of pre-C89 compilers, but it is defined in C89 and therefore is supported essentially everywhere. Apr 4, 2011 at 14:25
  • 4
    Also, if you really want the string formatted on multiple lines in c++98 just substitute \n for the terminating space on each quoted string fragment. C++11 raw literals are still my favorite.
    – emsr
    Sep 22, 2011 at 3:46
  • 3
    @unwind Note that newline at the end of source line is not made part of the string, it's just skipped. If you want a newline as part of the string, you need to have \n\ at the end of the line.
    – hyde
    Apr 21, 2013 at 7:39
  • 2
    There's nasty bug in Microsoft Visual Studio. If you use backslashes at the end of lines, then it automatically indents the text inside the string.
    – palota
    Jan 19, 2014 at 21:18
599

In C++11 you have raw string literals. Sort of like here-text in shells and script languages like Python and Perl and Ruby.

const char * vogon_poem = R"V0G0N(
             O freddled gruntbuggly thy micturations are to me
                 As plured gabbleblochits on a lurgid bee.
              Groop, I implore thee my foonting turlingdromes.   
           And hooptiously drangle me with crinkly bindlewurdles,
Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't.

                (by Prostetnic Vogon Jeltz; see p. 56/57)
)V0G0N";

All the spaces and indentation and the newlines in the string are preserved.

These can also be utf-8|16|32 or wchar_t (with the usual prefixes).

I should point out that the escape sequence, V0G0N, is not actually needed here. Its presence would allow putting )" inside the string. In other words, I could have put

                "(by Prostetnic Vogon Jeltz; see p. 56/57)"

(note extra quotes) and the string above would still be correct. Otherwise I could just as well have used

const char * vogon_poem = R"( ... )";

The parens just inside the quotes are still needed.

11
  • 35
    This is really what I want, the ability to avoid quotes, backslash-Ns, escapes, and still have newlines appear in the actual string. This is handy for embedded code (e.g. shaders or Lua). Unfortunately, we aren't all using C++-0x yet. :-(
    – mlepage
    Jul 18, 2012 at 14:40
  • 2
    I was considering this for embedded SQL and Python scripts myself. I was hoping for your sake if maybe gcc would let it slide through in C++98 mode but, alas, no.
    – emsr
    Jul 18, 2012 at 15:16
  • 3
    I am more used to clang and gcc. In thise compilers you have to set a flag for C++0x or c++11. Lookin n a MS website it looks like they don't have raw literals yet. i understand that MS will release new compiler updates more quickly as C++ features get implemented. Look for Visual C++ Compiler November 2012 CTP [microsoft.com/en-us/download/details.aspx?id=35515] for the latest bleeding edge.
    – emsr
    Jan 31, 2013 at 1:17
  • 5
    @rsethc Just use #if 0#endif to comment out blocks of code. Nests too.
    – bobbogo
    Sep 12, 2017 at 17:23
  • 1
    I don't suppose @rlbond would consider changing the accepted answer? The one currently accepted was correct at the time it was written, but this is definitely the proper answer for modern times. Feb 26, 2020 at 23:24
66

You can also do this:

const char *longString = R""""(
This is 
a very 
long 
string
)"""";
6
  • 2
    thanks, this is great, works even in C. obviously, char longString[] = R""""( This is a very long string )""""; works too, for me. Jun 15, 2019 at 18:02
  • 3
    Does this start and end the string with a new line?
    – Tim MB
    Oct 5, 2019 at 9:51
  • 2
    It's a raw string literal. Available since C++11.
    – Mikolasan
    Jan 25, 2020 at 0:57
  • 1
    works with Arduino! Now I can serve embedded web pages with ease!
    – nmz787
    Jul 19, 2020 at 9:52
  • A nice variation on @emsr that shows his answer can be made to look less like PERL and more like Python. Dec 18, 2020 at 1:46
32

#define MULTILINE(...) #__VA_ARGS__
Consumes everything between the parentheses.
Replaces any number of consecutive whitespace characters by a single space.

4
  • 1
    You can add \n if you need newlines
    – Simon
    Jul 1, 2013 at 14:11
  • Note that ` (and hence \n) is copied literally, but "` is converted into \". So MULTILINE(1, "2" \3) yields "1, \"2\" \3". Sep 11, 2013 at 12:58
  • @AndreasSpindler Quotes and backslashes alike are escaped by (additional) backslashes as long as they appear inside a string or character literal token. Not sure what's your point. It is illegal to have an unmatched quote (double or single), so contractions don't work, or an odd number of them anyway, which is probably the biggest downside. +1 anyway. "Real programmers" always use contractions in pairs with no intervening newline so the single quotes balance. Oct 14, 2013 at 4:28
  • The point is that he wrote "consumes everything between parentheses". Oct 14, 2013 at 14:33
31

A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:

#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
  Using this trick(,) you don't need to use quotes.
  Though newlines and     multiple     white   spaces
  will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);

Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]

Note that the , cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.

Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__ allows the use of ,.

4
  • For a project in which I wanted to include some lua code snippets in c++, I ended up writing a small python script, in which I entered the multiline strings, and let that generate a c++ source file.
    – bcmpinc
    Jul 16, 2012 at 16:39
  • Perfect for me, adding a huge multi-line float-list string from a collada file for unit testing. I didn't fancy putting quotes everywhere, I needed a copy&paste solution. Aug 1, 2012 at 11:39
  • 9
    You can use #define MULTILINE(...) #__VA_ARGS__ if you want your string to contain commas.
    – Simon
    Jul 1, 2013 at 14:09
  • 2
    Note this will strip out most extra whitesapce (including all \n and \r), which is kind of handy for some cases and fatal for others.
    – BCS
    Oct 8, 2013 at 21:35
29

You can just do this:

const char *text = "This is my string it is "
     "very long";
2
  • How is it any different than @unwind's answer?
    – Sisir
    Feb 8, 2020 at 13:50
  • 21
    @Sisir I posted it 2 minutes before unwind did.
    – Eric
    Feb 8, 2020 at 13:51
15

Just to elucidate a bit on @emsr's comment in @unwind's answer, if one is not fortunate enough to have a C++11 compiler (say GCC 4.2.1), and one wants to embed the newlines in the string (either char * or class string), one can write something like this:

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

Very obvious, true, but @emsr's short comment didn't jump out at me when I read this the first time, so I had to discover this for myself. Hopefully, I've saved someone else a few minutes.

0
12

Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE:

#define MULTILINE(...) #__VA_ARGS__

const char *mstr[] =
{
    MULTILINE(1, 2, 3),       // "1, 2, 3"
    MULTILINE(1,2,3),         // "1,2,3"
    MULTILINE(1 , 2 , 3),     // "1 , 2 , 3"
    MULTILINE( 1 , 2 , 3 ),   // "1 , 2 , 3"
    MULTILINE((1,  2,  3)),   // "(1,  2,  3)"
    MULTILINE(1
              2
              3),             // "1 2 3"
    MULTILINE(1\n2\n3\n),     // "1\n2\n3\n"
    MULTILINE(1\n
              2\n
              3\n),           // "1\n 2\n 3\n"
    MULTILINE(1, "2" \3)      // "1, \"2\" \3"
};

Compile this fragment with cpp -P -std=c++11 filename to reproduce.

The trick behind #__VA_ARGS__ is that __VA_ARGS__ does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__, saw the need for raw string literals.

9
// C++11. 
std::string index_html=R"html(
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VIPSDK MONITOR</title>
    <meta http-equiv="refresh" content="10">
</head>
<style type="text/css">
</style>
</html>
)html";
1
  • 18
    Please add an explanation to your answer and not just code snippets
    – Geordie
    May 26, 2020 at 23:49
-7

Option 1. Using Boost library, you can declare the string as below:

const boost::string_view helpText = "This is very long help text.\n"
      "Also more text is here\n"
      "And here\n"

// Pass help text here
setHelpText(helpText);

Option 2. If Boost is not available in your project, you can use std::string_view() in modern C++.

1
  • This is a C++ language feature. No relation to boost here.
    – sstn
    Mar 30 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.