We can define a string with multiline like this:
const char* text1 = "part 1" "part 2" "part 3" "part 4"; const char* text2 = "part 1\ part 2\ part 3\ part 4";
How about with raw literal, I tried all, no one works
std::string text1 = R"part 1"+ R"part 2"+ R"part 3"+ R"part 4"; std::string text2 = R"part 1" R"part 2" R"part 3" R"part 4"; std::string text3 = R"part 1\ part 2\ part 3\ part 4"; std::string text4 = R"part 1 part 2 part 3 part 4";
We can use string literal concatenation. Multiple string literals in a row are joined together: char* my_str = "Here is the first line." "Here is the second line."; But wait!
Raw String Literal in C++ A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ' \n, \t, or \” ' of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.
Using Backslash If we place a backslash at the end of each line, the compiler removes the new-line and preceding backslash character. This forms the multiline string.
They are not const in C, but are in C++. They aren't generally writable as noted by others, but they don't behave as constants.
Note that raw string literals are delimited by R"(
and )"
(or you can add to the delimiter by adding characters between the quote and the parens if you need additional 'uniqueness').
#include <iostream> #include <ostream> #include <string> int main () { // raw-string literal example with the literal made up of separate, concatenated literals std::string s = R"(abc)" R"( followed by not a newline: \n)" " which is then followed by a non-raw literal that's concatenated \n with" " an embedded non-raw newline"; std::cout << s << std::endl; return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With