字符型
作用: 字符型变量用于显示单个字符
语法: char ch = 'a';
1.C和C++中字符型变量只占用1个字节。
2.字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放入到存储单元。
#include<iostream>
using namespace std;
int main() {
char ch = 'a';
cout << ch << endl;
cout << sizeof(char) << endl;
//ch = "abcde"; //错误,不可以用双引号
//ch = 'abcde'; //错误,单引号内只能引用一个字符
cout << (int)ch << endl; //查看字符a对应的ASCII码
ch = 97; //可以直接用ASCII给字符型变量赋值
cout << ch << endl;
system("pause");
return 0;
}
字符串
作用: 用于表示一串字符
语法( C ): char 变量名[] = "字符串值";
语法( C++ ): string 变量名 = "字符串值";
c语言型:
#include<iostream>
using namespace std;
int main() {
char str1[] = "hello world";
cout << str1 << endl;
system("pause");
return 0;
}
c++语言型:(注意:C++风格字符串,需要加入头文件 #include )(vs2019可以不带)
#include<iostream>
#include<string>
using namespace std;
int main() {
string str = "hello world";
cout << str << endl;
system("pause");
return 0;
}
ASCII码
ASCII 码大致由以下两部分组成:
ASCII 非打印控制字符: ASCII 表上的数字 0-31 分配给了控制字符,用于控制像打印机等一些外围设备。
ASCII 打印字符: 数字 32-126 分配给了能在键盘上找到的字符,当查看或打印文档时就会出现。
转义字符
作用: 用于表示一些不能显示出来的ASCII字符
现阶段我们常用的转义字符有:\n \\ \t
#include<iostream>
using namespace std;
int main() {
cout << "\\" << endl;
cout << "\tHello" << endl;
cout << "\n" << endl;
system("pause");
return 0;
}