char类型是专门存储字符(字母和数字)的一种数据类型。
//chartype.cpp -- the char(字符和小整数) type
#include <iostream>
int main()
{
using namespace std;
char ch; //declare a char variable
cout << "Enter a character:" << endl;
cin >> ch;
cout << "Hola! ";
cout << "Thank you for the " << ch << " character.\n";
return 0;
}
C++对字符用单引号,对字符串使用双引号。
//morechar.cpp -- the char type and int type contrasted
#include <iostream>
int main()
{
using namespace std;
char ch = 'M'; //assign ASCII code for M to ch
int i = ch; //store same code in an int
cout << "The ASCII code for " << ch << " is " << i << endl;
cout << "Add one to the character code:" << endl;
ch = ch + 1; //change character code in ch
i = ch; //save new character code in i
cout << "The ASCII code for " << ch << " is " << i << endl;
//use the cout.put() member function to display a char
cout << "Dispaly char ch using cout.put(ch): ";
cout.put(ch);
//using cout.put() to display a char constant
cout.put('!');
cout << endl << "Done" << endl;
return 0;
}
char字面值的表示方法:
- 将字符用单引号括起来,这种表示法代表的是字符的数值编码。
- 有些字符不能直接通过键盘输入到程序中,可以用转义序列(escape sequence)。
字符名称 | ASCII符号 | C++代码 | 十进制ASCII码 | 十六进制ASCII码 |
换行符 | NL(LF) | \n | 10 | 0xA |
水平制表符 | HT | \t | 9 | 0x9 |
垂直制表符 | VT | \v | 11 | 0xB |
退格 | BS | \b | 8 | 0x8 |
回车 | CR | \r | 13 | 0xD |
振铃 | BEL | \a | 7 | 0x7 |
反斜杠 | \ | \\ | 92 | 0x5C |
问号 | ? | \? | 63 | 0x3F |
单引号 | ' | \' | 39 | 0x27 |
双引号 | " | \" | 34 | 0x22 |
注意:应该像处理常规字符(如 Q )那样处理转义序列(如 \n ),将它们作为字符常量时,应用单引号括起;将它们放在字符串中时,不要使用单引号。
//bondini.cpp -- using escape sequences(转义序列)
#include <iostream>
int main()
{
using namespace std;
cout << "\aOperation \"HyperHype\" is now activated!\n";
cout << "Enter your agent code:________\b\b\b\b\b\b\b\b";
long code;
cin >> code;
cout << "\aYou entered " << code << "...\n";
cout << "\aCode verified! Proceed with Plan Z3!\n";
return 0;
}
C++中的字符类型在支持标准字符集的基础上还支持通用字符名,在使用中通用字符名可以使用以 \u 或者 \U 开头的扩展字符集,\u 后加8个十六进制数据,\U 后加16个十六进制数据。
C++语言中使用 wchar_t 类型表示扩展字符集,其中 wchar_t 是一种整形数据,长度大于 char 类型,因此能够表示更多的字符类型,在处理 wchar_t 类型的变量时,可以使用 L 前缀来表示 wchar_t 类型,例如:
wchar_t bob = L'P';
为了解决计算机编码和字符集问题,C++11标准又增加了 char16_t 和 char32_t 类型,长度分别为无符号16位和32位,程序设计中分别使用 u 和 U 前缀表示。