Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiline string raw literal

Tags:

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"; 
like image 498
www.diwatu.com Avatar asked Dec 11 '13 00:12

www.diwatu.com


People also ask

How do you define multi line string literals?

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!

What is raw string literal?

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 )”.

How do you write a multiline string in C++?

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.

Are string literals const in C?

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.


1 Answers

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; } 
like image 156
Michael Burr Avatar answered Jan 01 '23 21:01

Michael Burr