C++学习笔记7:char类型

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)。
C++转义序列的编码
字符名称ASCII符号C++代码十进制ASCII码十六进制ASCII码
换行符NL(LF)\n100xA
水平制表符HT\t90x9
垂直制表符VT\v110xB
退格BS\b80x8
回车CR\r130xD
振铃BEL\a70x7
反斜杠\\\920x5C
问号?\?630x3F
单引号'\'390x27
双引号"\"340x22

注意:应该像处理常规字符(如 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 前缀表示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值