What is Raw string literal in C++?

Raw string literal

When we aim to print the escape characters like “\n” in C++, we use “\”. Otherwise, they are not displayed in the output.

In C++, escape characters like ("\n", “\t”, or “\”) can be shown on the output using a raw string literal as follows:

R"(a string containing escape characters)"

By placing R in front of the string will enable the escape characters to be printed as output.

Code example

The following code will show the difference between using a normal string and a raw string literal to print a string containing escape characters.

#include <iostream>
using namespace std;
int main()
{
// An ordinary string
string str1 = "Welcome.\nTo.\nEducative.\n" ;
// Raw string
string str2 = R"(Welcome.\nTo.\nEducative.\n)";
cout << "Normal string is: "<<endl<<str1 << endl;
cout <<"Raw string is: "<< str2 << endl;
return 0;
}

Another code example

This example again shows a normal string strN being declared. Then, another string strR is declared with a raw string literal.

Following this, both of the strings are printed and it shows how their output differs.

#include <iostream>
using namespace std;
int main() {
// Normal string
string strN = "learn\tat\tEducative" ;
// Same string but now with raw string literal
string strR = R"(learn\tat\tEducative)";
// Output normal string
cout <<"Normal string is: " << strN << endl;
// Output normal string
cout <<"Raw string is: " << strR << endl;
return 0;
}