Search code examples
c++io

How do we print multi-line content in c++ in an native and elegant way?


I am trying to print stuff like this like an exercise:

  *
 ***
*****
 ***
  *

and I have been using c++ to print every line in a separate statement. It can pass the tests all right.

However, I have learnt in python that we can do something like this:

s = """
  *
 ***
*****
 ***
  *
"""
print(s)

and it does the job neatly. So I have been wondering: Is there an elegant equivalent in c++? The searching I have used all need using \n or std::endl as line breaks, which I do not want to do.


Solution

  • Just use multiline string literals, like this :

    #include <iostream>
    
    const char *s= "  *  \n"
                   " *** \n"
                   "*****\n"
                   " *** \n"
                   "  *  \n";
    
    int main()
    {
        std::cout << s;
        return 0;
    }