c++stringstring-concatenationstring-literalsmultilinestring

How can I split a long string in source code into several lines for more readability in C++?


In other word how to make my code working if I don't want to write it one line?

#include <string>
using namespace std;

int main()
{
    string menu = "";
    menu += "MENU:\n"
        + "1. option 1\n"
        + "2. option 2\n"
        + "3. option 3\n"
        + "4. 10 more options\n";
}

Solution

  • Simply remove the +'s:

    #include <string>
    
    int main()
    {
        std::string menu = "MENU:\n"
            "1. option 1\n"
            "2. option 2\n"
            "3. option 3\n"
            "4. 10 more options\n";
    }
    
    

    Adjacent string literals are automatically concatenated by the compiler.

    Alternatively, in C++11, you can use raw string literals, which preserve all indentation and newlines:

    #include <string>
    
    int main()
    {
        std::string menu = R"(MENU:
    1. option 1
    2. option 2
    3. option 3
    4. 10 more options
    )";
    
    }