Create a multiline string literal in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string multiline_str = "The journey " "of a thousand miles " "begins with one step."; std::cout << multiline_str << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string multiline_str = "The journey \ of a thousand miles \ begins with one step."; std::cout << multiline_str << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string multiline_str = R"(The journey of a thousand miles begins with one step.)"; std::cout << multiline_str << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> #define MULTILINE_STRING(...) #__VA_ARGS__ int main() { std::string multiline_str = MULTILINE_STRING(The journey of a thousand miles begins with one step.); std::cout << multiline_str << std::endl; return 0; } |
Output:
The journey of a thousand miles begins with one step.
Or use below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> #define MULTILINE_STRING(s) #s int main() { std::string multiline_str = MULTILINE_STRING(The journey of a thousand miles begins with one step.); std::cout << multiline_str << std::endl; return 0; } |
Output:
The journey of a thousand miles begins with one step.
That’s all about creating a multiline string literal in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)