1.cin.get()
從指定的輸入流中提取一個字符,函數的返回值就是這個字符。文件結束符會返回EOF,一般以-1代表EOF。
1 #include<iostream> 2 using namespace std; 3 4 int main(){ 5 char c; 6 while((c=cin.get()!=EOF)) 7 cout.put(c); 8 return 0; 9 }
2.cin.get(ch)
讀取一個字符,賦值給ch,讀取成功返回非0值,讀取失敗(遇到文件結束符)返回0。
1 #include<iostream> 2 using namespace std; 3 4 int main(){ 5 char c; 6 while(cin.get(c)) 7 cout.put(c); 8 return 0; 9 }
3.cin.get(字符數組,字符個數n,終止字符)
或cin.get(字符指針,字符個數n,終止字符)
讀取n-1個字符,若在n-1個字符之前遇到終止字符,提前結束讀取。
1 #include<iostream> 2 using namespace std; 3 4 int main(){ 5 char c[20]; 6 cin.get(c,10,'\n'); 7 cout<<c<<endl; 8 return 0; 9 }
或者使用char*
1 #include<iostream> 2 using namespace std; 3 4 int main(){ 5 char* c; 6 c = new char[20]; //動態指針使用前需要分配內存 7 cin.get(c,10,'\n'); 8 cout<<c<<endl; 9 return 0; 10 }
4.cin.getline(字符數組(或指針),字符個數n,終止字符)
getline用法與帶三個參數的get函數類似。
1 #include<iostream> 2 using namespace std; 3 int main(){ 4 char c[20]; 5 cin.getline(c,20,'/'); 6 cout<<c<<endl; 7 return 0; 8 }
注意:
cin.getline與cin.get的區別:cin.get( , , )遇到終止字符停止讀取后,指針不向后移動;
cin.getline( , , )遇到終止字符結束后,指針移到終止字符后。
getline()是string類的函數
getline() // 接受一個字符串,可以接收空格並輸出,需包含“#include<string>”
和cin.getline()類似,但是cin.getline()屬於istream流,而getline()屬於string流,是不一樣的兩個函數
http://www.cnblogs.com/flatfoosie/archive/2010/12/22/1914055.html
http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html