C++ Special Characters

In C++, strings are enclosed in double quotes (" "), but certain characters need special handling to be properly displayed within text. Escape sequences allow programmers to insert special characters in a string without causing errors.

Tutorials dojo strip



Handling Special Characters with Escape Sequences

If a string contains quotation marks, C++ may misinterpret them, leading to an error.

Incorrect Example (Will Not Work)

C++

To fix this issue, use escape sequences with a backslash (\).




Common Escape Characters

A backslash (\) is used to insert special characters inside a string.

Escape CharacterResultDescription
\''Inserts a single quote
\""Inserts a double quote
\\\Inserts a backslash

Example: Using Double Quotes in Strings

If you need to include double quotes within a string, use \":

C++




Using Single Quotes (\')

To include apostrophes or single quotes, use \':

C++




Using a Backslash (\\)

To print a backslash character, use \\:

C++




Other Useful Escape Characters

Escape characters can also control formatting, allowing for text spacing or new lines.

Escape CharacterResultUsage
\nNew lineMoves text to the next line
\tTab spaceInserts a horizontal space

Example: Formatting a String

C++

Output:

C++

Tutorials dojo strip