Special Characters
Escape Sequences
In C++, special characters that cannot be typed directly or would otherwise be ambiguous are represented with escape sequences beginning with a backslash (\
):
Escape Sequence | Description |
---|---|
\n | New line (line feed) |
\r | Carriage return |
\t | Horizontal tab |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
\a | Alert (bell) |
\b | Backspace |
\f | Form feed |
\v | Vertical tab |
\0 | Null character (NUL); in C-style strings it marks the end, but std::string can contain it |
\xNN | Hex byte/char (e.g., \x41 == 'A') |
\uNNNN / \UNNNNNNNN | Unicode code point (UTF-16/UTF-32 escape) |
Examples
#include <iostream>
int main() {
std::cout << "Line 1\nLine 2\n";
std::cout << "Tab\tseparated\n";
std::cout << "Quote: \"Hello\"\n";
std::cout << "Path: C:\\Users\\Name\\file.txt\n";
return 0;
}
Line 1 Line 2 Tab separated Quote: "Hello" Path: C:\Users\Name\file.txt
Raw String Literals
C++11 introduced raw string literals, which treat backslashes and quotes literally without needing escape sequences. They are especially useful for file paths, JSON, or regular expressions.
#include <iostream>
#include <string>
int main() {
std::string path = R"(C:\Users\Name\file.txt)";
std::string json = R"({"name":"John","age":30})";
std::cout << path << '\n' << json;
return 0;
}
C:\Users\Name\file.txt {"name":"John","age":30}
Raw Strings with Custom Delimiters
If your content contains the sequence )"
, choose a custom delimiter so the compiler knows where the raw string ends.
// delimiter 'TAG' used on both sides
std::string tricky = R"TAG(He said: "Look for )" inside!" )TAG"; // literal )" inside
)TAG";
// Correct usage:
std::string ok = R"TAG(He said: "Look for )" inside!
)TAG"; // the delimiter is TAG
)TAG";
Unicode & Numeric Escapes
Use hex or Unicode escapes when you need characters not easily typed on your keyboard. Combine with UTF-8 literals when appropriate.
#include <iostream>
#include <string>
int main() {
char A = '\x41'; // 'A'
std::u8string deg = u8"\u00B0C"; // "°C" in UTF-8
std::cout << A << ' ' << (const char*)deg.c_str() << '\n';
return 0;
}
Pitfalls
- In ordinary string literals, backslashes must be doubled for Windows paths (use raw strings to avoid this).
- \0
is a character; inside std::string
it does not terminate the string automatically.
- Escape processing does not occur inside raw string literals.
- Prefer '\n'
for a newline without flushing; std::endl
adds a newline and flushes.