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,會使得包含指針的內存因爲做用域和對象生命週期的緣由而釋放,可是堆上動態分配的變量或結構卻還繼續存在。致使內存泄漏。