
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Raw String Literal in C++
Sometimes, in C++ when you try to print a string that containing special characters like escape sequences (\n), backslashes (\), or quotes(""), the output may not be as expected. To avoid this, C++ provides a feature called raw string literal. In this article, we will discuss what is raw string literal and how to use it in C++.
What is Raw String Literal?
A raw string literal in C++ is a type of string that preserves the formatting of the string content without changing any escape sequences such as "\n", "\t", or "". This is useful when you want to include special characters in your string without worrying about escaping them.
The syntax for a raw string literal is:
R"delimiter(raw_characters)delimiter"
Here, delimiter is optional and it can be a character except the backslash, whitespaces, and parentheses. The raw_characters can be any characters including escape sequences. The delimiter is just used to mark the beginning and end of the raw string literal.
Example of Raw String Literal
In the code below, we have show the difference between a normal string and a raw string literal. The normal string contains escape sequences which are interpreted by the compiler. But the raw string literal prints the string as it is.
#include <iostream> using namespace std; int main() { // Define a normal string with escape sequences string string1 = "Tutorialspoint.\n.provides.\t.best.\n.tutorials.\n"; // Define a raw string literal with escape sequences string string2 = R"(Tutorialspoint.\n.provides.\t.best.\n.tutorials.\n)"; // Print the strings cout << string1 << endl; cout << string2 << endl; return 0; }
The output of the above code will be:
Tutorialspoint. .provides. .best. .tutorials. Tutorialspoint.\n.provides.\t.best.\n.tutorials.\n
Multiline Raw String Literal
Raw string literals can also be used to create multiline strings. This way you can define an HTML or XML code inside C++ strings. The syntax is the same as above, you just need to add your HTML code inside the raw string literal. Let's see an example.
Example
In the code below, we have used a raw string literal to print an HTML code to C++ console.
#include <iostream> using namespace std; int main() { // Define a raw string literal with HTML code string htmlCode = R"( <html> <head> <title>My Web Page</title> </head> <body> <h1>Welcome to My Web Page</h1> <p>This is a simple web page.</p> </body> </html> )"; // Print the HTML code cout << htmlCode << endl; return 0; }
The output of the above code will be:
<html> <head> <title>My Web Page</title> </head> <body> <h1>Welcome to My Web Page</h1> <p>This is a simple web page.</p> </body> </html>