istream&get(unsigned char* pszBuf,int nBufLen,char delim=‘\n’);
istream&get(unsigned char* pszBuf,int nBufLen,char delim=‘\n’);
cin.getline()和cin.get()都是對輸入的面向行的讀取,即一次讀取整行而不是單個數字或字符,但是二者有一定的區別。
cin.get()每次讀取一整行並把由Enter鍵生成的換行符留在輸入隊列中(等待下次的讀取,如果下次再cin.get(),則就直接返回了,啥都沒有讀到,除非改變其的結束方式),比如:
#include <iostream>
using namespace std;
const int SIZE = 128;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.get(name,SIZE); //默認是以回車結束的
cout << "name:" << name;
cout << "\nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address<<endl;
return 0;
}
輸出:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:address:
在這個例子中,cin.get()將輸入的名字讀取到了name中,並將由Enter生成的換行符'\n'留在了輸入隊列(即輸入緩衝區)中,因此下一次的cin.get()便在緩衝區中發現了'\n'並把它讀取了,最後造成第二次的無法對地址的輸入並讀取。解決之道是在第一次調用完cin.get()以後再調用一次cin.get()把'\n'符給讀取了,可以組合式地寫爲cin.get(name,SIZE).get();。
cin.getline()每次讀取一整行並把由Enter鍵生成的換行符拋棄,如:
#include <iostream>
using namespace std;
const int SIZE = 128;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.getline(name,SIZE);
cout << "name:" << name;
cout << "\nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address;
}
輸出:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:YN QJ
address:YN QJ
由於由Enter生成的換行符被拋棄了,所以不會影響下一次cin.get()對地址的讀取。