字符型
/*字符型*/
#include <iostream>
using namespace std;
int main()
{
//字符型变量创建方式
char ch = 'a';
cout << ch << endl;
//字符型变量所占内存大小(1字节)
cout << sizeof(ch) << endl;
//字符型变量常见错误
//char ch2 = "b";创建字符型变量时要用单引号
//char ch3 = 'abcdef';//创建字符型变量时单引号内只能有一个字符
//字符型变量对应的ASCII码
//a-97
//A-65
cout << (int)ch << endl;
system("pause");
return 0;
}
转义字符
用于表示一些不能显示出来的ASCII字符
/*转义字符*/
#include <iostream>
using namespace std;
int main()
{
// 换行\n 反斜杠\\ 水平制表符\t
cout << "hello world!\n";
cout << "\\" << endl;
cout << "aaa\thello world" << endl;//n个a加\t总共是八格,因此可以整齐地输出数据
cout << "aaaaa\thello world" << endl;
cout << "aa\thello world" << endl;
system("pause");
return 0;
}
字符串型
用于表示一串字符
/*字符串型*/
#include <iostream>
#include <string> //用C++风格字符串时需包含这个头文件
using namespace std;
int main()
{
//C风格字符串
char str[] = "hello world";
cout << str << endl;
//C++风格字符串
string str2 = "hello world";
cout << str2 << endl;
system("pause");
return 0;
}
布尔类型
代表真或假的值
true 真 本质是1
false 假 本质是0
占一个字节大小
/*布尔类型*/
#include <iostream>
using namespace std;
int main()
{
//创建bool类型
bool flag = true;
cout << flag << endl;//本质为1
flag = false;
cout << flag << endl;//本质为0
//查看bool类型所占内存空间
cout << "bool类型所占内存空间:" << sizeof(bool) << endl;
system("pause");
return 0;
}
数据的输入
从键盘获取数据
cin>>变量
/*数据的输入*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
//1、整型
int a = 0;
cout << "请给整型变量a赋值:" << endl;
cin >> a;
cout << "整型变量a=" << a<< endl;
//2、浮点型
float f = 3.14f;
cout << "请给浮点型变量f赋值:" << endl;
cin >> f;
cout << "浮点型变量f=" << f << endl;
//3、字符型
char ch = 'a';
cout << "请给字符型变量ch赋值:" << endl;
cin >> ch;
cout << "字符型变量ch=" << ch << endl;
//4、字符串型
string str = "hello";
cout << "请给字符串型变量str赋值:" << endl;
cin >> str;
cout << "字符型变量str=" << str << endl;
//5、布尔类型
bool flag = true;
cout << "请给bool型变量flag赋值:" << endl;
cin >> flag;//bool类型只要是非零值都代表真
cout << "bool型变量flag=" << flag << endl;
system("pause");
return 0;
}