Even though the char

来源:互联网 发布:福建广电网络宽带帐号 编辑:程序博客网 时间:2024/06/03 16:48

Even though the char data type is an integer (and thus follows all of the normal integer rules), we typically work with chars in a different way than normal integers. Characters can hold either a small number, or a letter from the ASCII character set. ASCII stands for American Standard Code for Information Interchange, and it defines a mapping between the keys on an American keyboard and a number between 1 and 127 (called a code). For instance, the character ‘a’ is mapped to code 97. ‘b’ is code 98. Characters are always placed between single quotes.

The following two assignments do the same thing:

1
2
charchValue = 'a';
charchValue2 = 97;

cout outputs char type variables as characters instead of numbers.

The following snippet outputs ‘a’ rather than 97:

1
2
charchChar = 97; // assign char with ASCII code 97
cout << chChar; // will output 'a'

If we want to print a char as a number instead of a character, we have to tell cout to print the char as if it were an integer. We do this by using a cast to have the compiler convert the char into an int before it is sent to cout:

1
2
charchChar = 97;
cout << (int)chChar;// will output 97, not 'a'

The (int) cast tells the compiler to convert chChar into an int, and cout prints ints as their actual values. We will talk more about casting in a few lessons.

The following program asks the user to input a character, then prints out both the character and it’s ASCII code:

1
2
3
4
5
6
7
8
9
10
#include "iostream";
 
intmain()
{
    usingnamespace std;
    charchChar;
    cout << "Input a keyboard character: ";
    cin >> chChar;
    cout << chChar << " has ASCII code " << (int)chChar << endl;
}

Note that even though cin will let you enter multiple characters, chChar will only hold 1 character. Consequently, only the first character is used.

One word of caution: be careful not to mix up character (keyboard) numbers with actual numbers. The following two assignments are not the same

1
2
charchValue = '5';// assigns 53 (ASCII code for '5')
charchValue2 = 5; // assigns 5

Escape sequences

C and C++ have some characters that have special meaning. These characters are called escape sequences. An escape sequence starts with a \, and then a following letter or number.

The most common escape sequence is ‘\n’, which can be used to embed a newline in a string of text:

1
2
3
4
5
6
7
8
#include <iostream>
 
intmain()
{
    usingnamespace std;
    cout << "First line\nSecond line" << endl;
    return0;
}

This outputs:

First lineSecond line

Another commonly used escape sequence is ‘\t’, which embeds a tab:

1
2
3
4
5
6
7
#include <iostream>
 
intmain()
{
    usingnamespace std;
    cout << "First part\tSecond part";
}

Which outputs:

First part        Second part
0 0