Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING3.7 Printing Characters Based on Numbers, Take 2
1: #include <iostream>
2: int main()
2: {
4: for (unsigned char i = 32; i<128; i++)
5: std::cout << i;
6: return 0;
7: }

As you can see, an unsignedcharacter is used on line 4. Because a character variable is
being used instead of a numeric variable, the couton line 5 knows to display the charac-
ter value.

Special Printing Characters ..............................................................................


The C++ compiler recognizes some special characters for formatting. Table 3.3 shows
the most common ones. You put these into your code by typing the backslash (called the
escape character), followed by the character. Thus, to put a tab character into your code,
you enter a single quotation mark, the slash, the letter t, and then a closing single quota-
tion mark:
char tabCharacter = ‘\t’;
This example declares a charvariable (tabCharacter) and initializes it with the charac-
ter value \t, which is recognized as a tab. The special printing characters are used when
printing either to the screen or to a file or other output device.
The escape character (\) changes the meaning of the character that follows it. For exam-
ple, normally the character n means the letter n, but when it is preceded by the escape
character, it means new line.

TABLE3.3 The Escape Characters
Character What It Means
\a Bell (alert)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Ta b
\v Vertical tab
\’ Single quote

58 Day 3

Free download pdf