Write Long Strings in Multi-lines in C/C++



To write long strings in multi-lines, you can use 'newline character' or 'raw string literal'. It increases the readability of the code, makes the code look clean, and you can avoid scrolling.

In this article, we have a long string and our task is to write the long string in multi-lines in C++.

Approaches to Write Long Strings in Multi Lines

Here is a list of approaches to write long strings in multiple lines which we will be discussing in this article with stepwise explanation and complete example codes.

Using Newline Character

In this approach, we have used the newline character (\n) to write the long string into multiple lines. The newline character (\n) inserts a line break that breaks the long string into multiple lines.

Example

The following example uses the newline character (\n) to break long string into multiple lines:

#include <iostream>
using namespace std;

int main() {
    string longString = "This is a very long string.\n"
                        "It will be distributed in\n"
                        "multiple lines. Say Hello world!";
    cout << longString;
    return 0;
}

Using Raw String Literals

For writing long strings in multiple lines, you can use the raw string literal. The raw string literal lets you display the string as you write the strings in the program. It can be used to print escape characters like (\n), or (\t).

Example

In this example, we break a long string into multiple lines using the raw string literal.

#include <iostream>
using namespace std;

int main() {
    string longString = R"(This is a very long string.
It will be distributed in
multiple lines. Say Hello world!)";
    cout << longString;
    return 0;
}
Updated on: 2025-04-10T10:24:43+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements