4.10 Characters

I l @ ve RuBoard

4.10 Characters

The type char represents single characters. The form of a character declaration is:

 char   variable   ;   //   comment   

Characters are enclosed in single quotation marks ( ' ). 'A' , 'a' and '!' are character constants. The backslash character (\) is called the escape character . It is used to signal that a special character follows . For example, the character \t can be used to represent the single character "tab." \n is the newline character. It causes the output device to go to the beginning of the next line, similar to a return key on a typewriter. The character \\ is the backslash itself. Finally, characters can be specified by \ nnn , where nnn is the octal code for the character. Table 4-3 summarizes these special characters. For a full list of ASCII character codes, see Appendix A.

Table 4-3. Special characters

Character

Name

Meaning

\b

Backspace

Move the cursor to the left one character.

\f

Form feed

Go to top of a new page.

\n

New line

Go to the next line.

\r

Return

Go to the beginning of the current line.

\t

Tab

Advance to the next tab stop (eight-column boundary).

\'

Apostrophe or single quotation mark

The character '.

\"

Double quote

The character ".

 \ 

Backslash

The character \.

\ nnn

The character nnn

The character number nnn (octal).

\xNN

The character NN

The character number NN (hexadecimal).

While characters are enclosed in single quotes ( ' ), a different data type, the string literal, is enclosed in double quotes ( " ). A good way to remember the difference between these two types of quotes is that single characters are enclosed in single quotes. Strings can have any number of characters (including double quote characters), and they are enclosed in double quotes.

Example 4-5 demonstrates the use of character variables by reversing three characters.

Example 4-5. print3/print3.cpp
 #include <iostream> char char1;     // first character  char char2;     // second character char char3;     // third character  int main(  ) {     char1 = 'A';     char2 = 'B';     char3 = 'C';     std::cout << char1 << char2 << char3 << " reversed is " <<             char3 << char2 << char1 << "\n";     return (0); } 

When executed, this program prints:

 ABC reversed is CBA 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net