1. 程式人生 > >cin.getline()和cin.get() 的區別

cin.getline()和cin.get() 的區別

cin.getline()和cin.get()都是對輸入的面向行的讀取,即一次讀取整行而不是單個數字或字元,但是二者有一定的區別。
cin.get()每次讀取一整行並把由Enter鍵生成的換行符留在輸入佇列中,比如:

#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
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;
}

輸出:
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 std::cin;
using std::cout;
const int SIZE = 15;
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()對地址的讀取。

 

兩點注意:

(1) 學會區別get()與getline();

(2)換行符號是\n,而不是/n;

一點體會:

程式設計得多動手,多思考.