1. 遍歷數組
- 使用基於范圍的for循環來遍歷整個數組
- 用_countof()來得到數組中的元素個數
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int main(){ 5 int arr[]={11,12,13,14,15}; 6 //_countof用於輸出數組里面元素個數 7 cout<<_countof(arr)<<endl; 8 9 for(int i:arr){ 10 //i 是指定訪問的那個變量。存放數組里面的元素 11 cout<<"I am "<<i; 12 printf("\n"); 13 } 14 cout<<endl<<"end"; 15 return 0; 16 }

2.字符串數組的輸入
- 常用cin.getline(name,MAX,'\n')
cin 為 istream類的對象,調用getline函數。
- name是該數組的名字
- MAX是輸入的字符最大個數
- 最后的是結束的標志。
以下兩個條件達到,將結束輸入。
1. 達到MAX-1, 2. 遇到最后的標志(常常是'\n')
- 用for循環來遍歷數組
1 #include <iostream> 2 using namespace std; 3 int main(){ 4 const int MAX=10; 5 char c1[MAX]; 6 cout<<"What's your favourite subject?"<<endl; 7 //從外設讀取流,遇到'\n'結束 8 cin.getline(c1,MAX,'\n'); 9 cout<<"Your favourite subject is "<<c1<<endl; 10 int counter(0); 11 for(auto i:c1){ 12 //將從0遍歷到MAX 13 cout<<(++counter)<<" : "<<i<<"\t"; 14 } 15 return 0; 16 }

3. 指針數組
1 #include <iostream> 2 using namespace std; 3 int main(){ 4 //數組指針,數組中的五個元素,均指向一個char[]的串 5 char *psubject[]={ 6 "English", 7 "Math", 8 "Physics", 9 "Chinese", 10 "Chemistry" 11 }; 12 cout<<"Enter 1-5 to get a subject"<<endl; 13 int chooice; 14 cin>>chooice; 15 //psubject這個指針的第n個,為一個數組,可以直接輸出 16 if(chooice>=1&&chooice<=5) 17 cout <<"what you chose is "<< psubject[chooice-1]; 18 return 0; 19 }

4. sizeof
sizeof用於輸出所占的字節。sizeof為一個「操作符」,得到的結果為無符整形。
1 int i=1; 2 cout<<sizeof i;
結果為4,因為int類型的 i 要占4個字節。
