2

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";
}
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Denys_newbie
  • 1,140
  • 5
  • 15

3 Answers3

6

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
)";

}
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
2

You don't need the +s. By just leaving those out, the compiler will concatenate all the string literals into one long string:

menu += "MENU:\n"
    "1. option 1\n"
    "2. option 2\n"
    "3. option 3\n"
    "4. 10 more options\n";
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

Just remove the add operators in your example. Consecutive strings with nothing between them are simply concatenated. So, for example, the two consecutive tokens "hello " "world" is the same as "hello world". But keep in mind that source code line breaks can separate any two tokens, so "hello " and "world" can be on separate lines, just as you wish.

Larry Ruane
  • 137
  • 6