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.
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 stringstring str1 = "Welcome.\nTo.\nEducative.\n" ;// Raw stringstring str2 = R"(Welcome.\nTo.\nEducative.\n)";cout << "Normal string is: "<<endl<<str1 << endl;cout <<"Raw string is: "<< str2 << endl;return 0;}
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 stringstring strN = "learn\tat\tEducative" ;// Same string but now with raw string literalstring strR = R"(learn\tat\tEducative)";// Output normal stringcout <<"Normal string is: " << strN << endl;// Output normal stringcout <<"Raw string is: " << strR << endl;return 0;}