Escape Sequences


 

Sample program

#include <iostream>
using namespace std;
int main()
{
   cout << "\nThis is\t a string\n\t\t"
           " with \"many\" escape sequences!\n";
   return 0;
} 

Program output:

  This is         a string
                  with "many" escape sequences! 

Using Control and Special Characters

Nongraphic characters can be expressed by means of escape sequences, for example \t, which represents a tab.
The effect of an escape sequence will depend on the device concerned. The sequence \t, for example, depends on the setting for the tab width, which defaults to eight blanks but can be any value.
An escape sequence always begins with a \ (backslash) and represents a single character. The table on the opposite page shows the standard escape sequences, their decimal values, and effects.
You can use octal and hexadecimal escape sequences to create any character code. Thus, the letter A (decimal 65) in ASCII code can also be expressed as \101 (three octals) or \x41 (two hexadecimals). Traditionally, escape sequences are used only to represent non-printable characters and special characters. The control sequences for screen and printer drivers are, for example, initiated by the ESC character (decimal 27), which can be represented as \33 or \x1b.
Escape sequences are used in character and string constants.
Examples:
'\t'    "\tHello\n\tMike!" 
The characters ', ", and \ have no special significance when preceded by a backslash, i.e. they can be represented as \', \", and \\ respectively.
When using octal numbers for escape sequences in strings, be sure to use three digits, for example, \033 and not \33. This helps to avoid any subsequent numbers being evaluated as part of the escape sequence. There is no maximum number of digits in a hexadecimal escape sequence. The sequence of hex numbers automatically terminates with the first character that is not a valid hex number.
The sample program on the opposite page demonstrates the use of escape sequences in strings. The fact that a string can occupy two lines is another new feature. String constants separated only by white spaces will be concatenated to form a single string.
To continue a string in the next line you can also use a backslash \ as the last character in a line, and then press the Enter key to begin a new line, where you can continue typing the string.
Examples:
"I am a very, very \
long string" 
Please note, however, that the leading spaces in the second line will be evaluated as part of the string. It is thus generally preferable to use the first method, that is, to terminate the string with " and reopen it with ".

Post a Comment

0 Comments