Using some popular escape sequence characters.
Using some escape sequences in c++ for common tasks.
Learning Objectives
- Learning to use special character displays in string and character literals using escape sequences.
Source Code
|
Run Output
Code Understanding
cout<<“Taj Mahal is in India\n”;
Here the \n character is called the new line character. It bring the cursor to one line down and then moves to starting of line in next page. Operating system will usually convert this character to two characters called \n and \r which are newline character (OA) and carriage return character (0D).
cout<<“Marks in Computers\t95″<<endl;
The \t character here is the tab character which moves the cursor to defined width towards the right side. Usually this defaults to 8 characters movement towards the right side. In this example 95 will be printed after 8 spaces from the previous string.
cout<<“How are you\?”<<endl;
The \? escape sequence is compiler dependent, however when given with \ character it will always print the ? character only. Mostly the ? character can be given directly also.
cout<<“\\ is a special character”<<endl;
Since character itself is for marking an escape sequence so if you want to print it in an string you will have to use it twice .
cout<<“This is \”string literal\””<<endl;
Since ” characters are string delimiters so if they have to be printed they need the escape sequence form as ” .
cout<<“\’C\’ is father of \”C++\””<<endl;
The escape sequence for is required for single quote also as \’
cout<<“\\101 is octal representation of “<<‘\101′<<endl;
The octal number given here as character literal ‘101’ means the decimal value 65 is used which is character A as per ascii code. To use two digit octal code we will still write 3 digits for e.g. for 71 octal we will write 71 (This will be decimal 57 – the ascii code for 9).
cout<<“\\x41 is hexadecimal representation of “<<‘\x41′<<endl;
The hexadecimal number can also be given by prefixing it with \x. Here the character literal ‘\x41’ is the ascii code of character A, so it will be printed.
cout<<“Null character is written as \\0″<<endl;
The null character is used in case of character arrays to check for null-terminated strings. It is a non-printable character and it is the first character of the ascii code.
Notes
- The full chart of escape sequence can be referred from –
http://en.cppreference.com/w/cpp/language/escape - Please do refer ASCII chart for more clear understanding.
http://en.cppreference.com/w/cpp/language/ascii
Common Errors
- This is a very error prone code so extreme care is required in putting character at every place.
Suggested Filename(s): esc-seq.cpp
sunmitra| Created: 6-Jan-2018 | Updated: 15-Nov-2018|