虽然char数据类型为整数(并因此遵循所有的规则,我们正整数)通常是以不同的方式比整数字符正常工作。人物可以拿一个小数目,或者一封从ASCII字符集。ASCII代表美标信息交换代码,它定义之间的键映射在美国的一个键盘和1和127之间的数(称为码)。例如,字母“A”映射到代码97。B是98码。人物总是放在单引号。
下面的两个任务做同样的事情:
1
2
char chValue = 'a';
char chValue2 = 97;
cout outputs char type variables as characters instead of numbers.
The following snippet outputs ‘a’ rather than 97:
1
2
char chChar = 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
char chChar = 97;
cout << (int)chChar; // will output 97, not 'a'
1
2
3
4
5
6
7
8
9
10
#include "iostream";
int main()
{
using namespace std;
char chChar;
cout << "Input a keyboard character: ";
cin >> chChar;
cout << chChar << " has ASCII code " << (int)chChar << endl;
}