short months[12] = {1};
处理字符串有两种ios
一种是C语言,C-风格字符串。 另外一种是基于string类库。数组
char cat[5] = {'f', 'a', 't', 's', '\0'};
注意: char数组最后应该以空字符结尾,cout打印字符串时,会打印直到遇到空字符为止。安全
更简单的声明方法, 结尾隐式的包含空字符:spa
char cat[] = "fats";
计算字符数组长度指针
strlen(cat)
#include <iostream> using namespace std; int main() { cout << "请输入出生年份:"; int year; cin >> year; cout << "请输入姓名:"; char name[20]; cin.getline(name, 20); cout << "用户" << name << ", 您出生于" << year << "年"; return 0; }
存在问题:code
当输入年份后,系统跳过输入姓名。对象
缘由是:生命周期
cin读完年份后,输入队列中留下了回车的换行符。cin.getline时,直接将空行赋值给姓名数组。队列
解决:内存
在调用getline以前,调用一次get(),清空回车。
声明
#include <cstring> using namespace std; string name;
结构用于存储多种类型的数据
#include <cstring> using namespace std; //声明 struct student { string name; int age; string gender; union { long id_num; char id_char[10]; }id; }; //初始化 student miku = { "miku", 18, "girl" };
//共同体 union { long id_num; char id_char[10]; }id; //匿名共同体 union { long id_num; char id_char[10]; };
枚举量:每一个枚举值都有对应整数值,从0开始
//声明 enum color{ red, orange, yellow }; //初始化 color a = red;
能够根据枚举量取值
color b = color (2); //b为orange
枚举能够提高为int,值为枚举量
int c = yellow; //c值为2
在声明枚举时能够对枚举量进行赋值
enum color{ red = 1, orange = 4, yellow = 8 };
指针: 指针是一个变量,存储的是值的地址。
对一个变量取地址:变量前面加地址操做符(&)
&home
#include <iostream> int main() { using namespace std; int updates = 6; int *p_updates; p_updates = &updates; cout << "Values: update= " << updates << endl; cout << "p_update= " << *p_updates << endl; *p_updates += 1; cout << "after updated" << endl; cout << "Values: update= " << updates << endl; cout << "p_update= " << *p_updates << endl; return 0; }
update表示一个值, &update表示该值的地址。
p_update表示指针(地址),*p_update表示该地址指向的值。
int *p_updates; *p_updates = &updates;
特别注意:
必定要在对指针应用解除引用操做符(*)以前,将指针初始化为一个肯定恰当的地址。
int *p_update; p_update = (int *)0xB13123;
int *pt = new int; *pt = 12;
当内存耗尽的状况下,new 将返回0。
值为0的指针被称为空值指针。
int *ps = new int; delete ps;
delete只能用来释放new 分配的内存。不过,对空指针使用delete是安全的。
int *psome = new int[10]; delete[] psome;
能够使用角标来操做动态数组。
修改指针的值,+1等价于指向第二个元素。
int *psome = new int[10]; psome[0] = 1; psome[1] = 2; psome[2] = 3; cout << psome[0] << ":" << psome[1] << ":" << psome[2]; cout << endl; cout << *psome << ":" << *(psome+1) << ":" << *(psome+2); delete[] psome;
若是new操做符在建立变量后,没有调用delete,会使得包含指针的内存因为做用域和对象生命周期的缘由而释放,可是堆上动态分配的变量或结构却还继续存在。致使内存泄漏。