How to create multi-line strings in C++

Asked

Viewed 198 times

3

Have some way to print output, for example a text, without having to print line by line?

For example, in Python:

print("""
Meu nome eh Guilherme, 
tenho 19 anos, faço aniversário em Nov.
Estudo o curso de ciência da computação.
(+ 4 linhas abaixo)
""")

Could you do something like that in C++? Or would I have to keep using cout and \n to do something similar?

1 answer

5


You can use the symbol already used to escape special characters to indicate that the text continues on the next line.

#include <iostream>
using namespace std;

int main() {
    cout << "isto é um teste \
de texto multi linha \
que pode ser usado em qualquer contexto de string";
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that the tab would be part of the text so I had to paste at the beginning of the line, but this is the same as other languages (I’ve seen some that disregard normal indentation, strange that Python does not do this, is the language that should do most).

It is also possible to use like this:

"isto é um teste "
"de texto multi linha "
"que pode ser usado em qualquer contexto de string"

But in general it does not produce what you want, since there is no line break, and it is strange to have to put in hand a \n. There you can obviously indent each part of the text outside the quotes.

Performance is not affected. On the contrary, if you do a concatenation it can affect, if the compiler can’t do an optimization because it would have a processing instead of this way which is just a different syntax.

  • Noooooossa, you saved absurdly!! Very much so!

  • I have one question only, in terms of performance and efficiency which is better? line by line equal I did or this way I asked?

  • It doesn’t change anything, it’s just syntax.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.