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";
}
3
  • 5
    Did you try just getting rid of the +s? Commented Apr 12, 2020 at 23:25
  • 1
    Yeah, nothing would be changed Commented Apr 12, 2020 at 23:28
  • "1. option 1\n" underlined red, and when I hover it it says expression must have integral or uscoped enum type. Commented Apr 12, 2020 at 23:31

3 Answers 3

7

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

}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

To clarify, the compiler will concatenate any two consecutive strings, e.g. "a" "b" into "ab".
@IlCapitano Reworded a bit
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.

2 Comments

may be you omitted 'not' particle after word 'can' in last sentance?
@Denis_newbie — no, the last sentence is correct. They can be on separate lines.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.