This post will discuss how to create a multiline string literal in C++.

1. Using string literals

C++ offers implicit string concatenation, where two or more string literals are joined together by the compiler if they are adjacent. This implicit concatenation can be used to create a multiline string literal in C++, as shown below:

Download  Run Code

Output:

The journey of a thousand miles begins with one step.

2. Using Backslash

If we place a backslash at the end of each line, the compiler removes the new-line and preceding backslash character. This forms the multiline string. Unlike the previous approach, indentation matters here.

Download  Run Code

Output:

The journey of a thousand miles begins with one step.

3. Using Raw String Literals

The best option to form a multiline string literal is using the raw string literal. This solution is short and elegant, but it is available only with C++11. Note that all spaces, newlines, indentations in the string are preserved.

Download  Run Code

Output:

The journey
of a thousand miles
begins with one step.

4. Using Macros

Finally, we can use macros to create a multiline string in C++. The indentation does not matter here, and the solution replaces multiple consecutive whitespace characters with a single space.

Download  Run Code

Output:

The journey of a thousand miles begins with one step.

 
Or use below:

Download  Run Code

Output:

The journey of a thousand miles begins with one step.

That’s all about creating a multiline string literal in C++.