Escape sequence in C/C++

Escape sequence in C/C++

When a character is preceded by a backslash ‘ \ ‘, it’s called an escape sequence. It has a specific action to perform by the compiler. They are used inside a character or string. \ Backslash is the escape character. \ is followed by other character which do not get printed with the string. They instead modify the format of the string. Let’s see a few escape sequence in C/C++.

1. \a => Produces Alert/Beep sound
cout<<“Hello\a (Audible sound) “;
Output- Hello (Audible sound)

2. \b => Backspace a character
cout<<“Hello\b World”;
Output- Hell World

3. \n => New line
cout<<“Error\nFree\nProgram”;
Output-
Error
Free
Program

4. \r => Carriage return-Positions the cursor at the beginning of the line and overwrites it
cout<<“ErrorFreeProgram\rHii”;
Output-
HiiorFreeProgram

5. \t => Horizontal tab
cout<<“Error\tFree\tProgram”;
Output-
Error Free Program

6. \v => Vertical tab
cout<<“Error\vFree\vProgram”;
Output-
Error
Free
Program

7. \’ => Print ‘ single quotes
cout<<‘\”;
Output- ‘

8. \” => Print ” double quotes
cout<<“\””;
Output- “

9. \\ => Print \ backslash
cout<<“D:\\Programs”;
Output- D:\Programs

10. \0 => Null character-Termination of the string
cout<<“Program\0ing”;
Output- Program

Let’s see a program in C++ to know the use of escape sequences.

Output-

escape sequence output

Note: Output depends on the compiler

#include<iostream>
using namespace std;
int main(){
    cout<<" Hello everyone! \a"; //  "\a"
    cout<<" @errorfreeprogramx\b"; //   "\b"
    cout<<" \n"; // "\n"
    cout<<" ErrorFreeProgram\r Hii"; // "\r"
    cout<<"\n "<<"1\t2"; // "\t"
    cout<<"\n"<<" Error\vFree\vProgram"; // "\v"
    cout<<"\n "<<'\''; //   "\'"
    cout<<"\n "<<"\""; //   "\""
    cout<<"\n "<<"D:\\Programs"; // "\\"
    cout<<"\n "<<"Program\0ing"; // "\0"
    return 0;
}

Conclusion-

So these were the escape sequence in C/C++. Hope you find these helpful.♥ Tell us if you like in the comment section. Share it with your friends and programming buddies.

For more such content follow us on Instagram. Do visit again!

ErrorFreeProgram.

2 COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *