"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Create Multi-Line String Literals in C++?

How Can I Create Multi-Line String Literals in C++?

Published on 2024-12-28
Browse:967

How Can I Create Multi-Line String Literals in C  ?

Multi-Line String Literals in C

In C , defining a multi-line string literal is not as straightforward as it is in some other languages like Perl. However, there are a few techniques you can use to achieve this:

Concatenated String Literals

One method is to utilize the fact that adjacent string literals in C are concatenated by the compiler. By breaking your string into multiple lines, you can create a single, multi-line string:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

Note that the indentation doesn't matter as it falls outside the quotes.

String with Escaped Newlines

Another approach involves using a string literal with escaped newlines. Instead of using newline characters in the string itself, you can escape them with backslashes (\) like so:

const char *text2 =
  "Here, on the other hand, I've gone crazy \\\
and really let the literal span several lines, \\\
without bothering with quoting each line's \\\
content. This works, but you can't indent.";

Remember, the backslashes must be immediately before the end of each line to escape the newline. This method works but prevents indentation from being preserved.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3