C++ 中輸入輸出細節

1)數組初始化

1.1 整數未賦值元素爲0 

int a[4]={2,3}; 
//結果 a[0]=2; a[1]=3; a[2]=0; a[3]=0;
//可以利用此性質,初始化所有元素爲0;

1.2 字符數組未賦值爲'\0',“賦值” 只能在初始化時進行


1.3 字符串數組初始化

char c[]="China";// 長度爲6, 末尾自動補'\0'
char c[]={'C','h','i','n','a'}; 長度5位
char c[5]="China"; //錯誤
//所有字符串以'\0'結尾
 字符串= 字符數組+'\0'


2) 輸入一個字符


// 2.1 cin  跳過 空格、回車
// Example:
while(cin>>c)
    cout<<c;
// 運行模擬:
//  I:abc def g
//  O:abcdefg

//小提示,利用ctrl+z 結束輸入

// 2.2 cin.get() 不跳過空格、回車
// Example:
while((c=cin.get())!= EOF)
    cout<<c;
// 運行模擬:
//  I:abc def g
//  O:abc def g


// 2.3 另一種寫法 cin.get(char)
// Example:
while(cin.get(c))
    cout<<c;
// 運行模擬:
//  I:abc def g
//  O:abc def g

//小提示,利用ctrl+z 結束輸入



//2.4 getchar() 不跳過任何字符 包括ctrl+z
// Example:
while(c=getchar())
    cout<<c;
// 運行模擬:
//  I:abc def g
//  O:abc def g
////小提示,利用ctrl+z 不再有效,需要利用ctrl+C 強制退出



3) 輸入字符串

// 輸入字符串
//
//    char str[5]={'C','h'};
//    cout<<str<<endl;
//    cout<<sizeof(str)<<endl;
//    //Firstly, the sizeof() operator does not give you the number of elements in an array,
//    //it gives you the number of bytes a thing occupies in memory. Hence:
//    // str[]="Ch" sizeof(str) return 3
//    // str[]={'C','h'}               2

////3.1 cin
//while(cin>>str)
//  cout<<str<<endl;
//輸入:how are you
//how
//are
//you
//^Z
//
//Process returned 0 (0x0)   execution time : 9.231 s
//Press any key to continue.

//
////3.2 cin.get()buffer 指針停止在結束符
// cin.get(字符數組,字符數n,終止符(默認\n))
//    cin.get(ch,20,'\n');
//    cout<<ch<<endl;;
//
//輸入:how are you
//how are you
//
//Process returned 0 (0x0)   execution time : 6.170 s
//Press any key to continue.

//3.3 cin.getline() buffer指針停在終止符後
// cin.getline(字符數組(或字符指針),字符個數n,終止標誌字符)
//    cin.getline(ch,20,'\n');
//    cout<<ch<<endl;
//how are you
//how are you
//
//Process returned 0 (0x0)   execution time : 5.791 s
//Press any key to continue.


圖片來自:coursera 公開課 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章