Learn How To Use C++ Raw String Literals For Windows Apps In C++ Builder
There are escape characters in C++ like “n” or “t”. When we try to print the escape characters, it will not display on the output. To show the escape characters on the output screen we use a raw string literal by using R”(String with escape characters)”. After using R in the front of the string the escape character will be displayed on the output.
From C++ 11, basically a raw string literal is a string in which the escape characters (like n t or ” ) of C++ are not processed. A raw string literal starts with R”( and ends in )”, let’s see an in an example the difference between a normal string and a raw string in C++:
using namespace std;
int main()
{
string normal_str=”First line.nSecond line.nEnd of message.n”;
string raw_str=R”(First line.nSecond line.nEnd of message.n)”;
cout
#include #include
using namespace std; int main() { string normal_str=“First line.nSecond line.nEnd of message.n”; string raw_str=R“(First line.nSecond line.nEnd of message.n)”; cout<<normal_str<<endl; cout<<raw_str<<endl; return(0); } |
The variable normal_str will be processed at compilation time so you will see three lines of text and an empty line. In the case of the variable raw_str which is a raw string literal, the compiler will not process the escape characters, so you will see a single line of text with a content identical with what you have in the C++ source code.
A first application of the concept of a raw string is in simplifying the syntax of the regular expressions. Take as an example the regular expression used in the regex tutorial for checking if the user input is an integer number. Without raw strings this is how the code should look:
regex integer(“(+|-)?[[:digit:]]+”); |
Using a raw string we can simplify the above piece of code, we can get rid of the escaping characters:
regex integer(R“((+|-)?[[:digit:]]+)”); |
Head over and get more information about C++ raw string literals in the Embarcadero DocWiki.