最原始的方法:
獲取輸入流最原始的形式就是cin>>(type) ,但是這種形式在碰到輸入中有空格、制表符或者換行符的時候就會中斷,值得注意的是中斷后空格、制表符或者換行符還繼續留在輸入流中。所以最簡單的,我們無法使用cin>>(type)的形式來讀取包含空格的字符串,比如輸入流中有一句:How are you?使用cin>>(type)是無法一次性讀取出來的,鑒于此,getline()方法和get()方法便誕生了。
getline()方法:
getline()方法讀取整行,他使用通過回車鍵輸入的換行符來中斷,getline()方法有兩個參數,第一個參數用來存儲輸入行的數組的名稱,第二個參數用來表示讀取字符數的大小。getline(name,size)的方法的使用過程如下:
1. 從輸入流中讀取一個字符。
2. 如果讀取數量達到size-1,將該字符存儲到name數組,刪除輸入流中的該字符,跳轉到5。
3. 如果該字符是換行符,刪除輸入流中的該字符,跳轉到5。
4. 否則,將該字符存儲到name數組,刪除輸入流中的該字符,跳轉到1。
5. 在name中結尾添加空字符,結束。
下面的代碼是使用原始方法和getline()方法的比較:
#include <iostream>using namespace std;int main(){ const int arrayLength = 20; char name1[arrayLength]; char name2[arrayLength]; cout<<"Enter your name1:/n"; cin>>name1; cout<<"Enter your name2:/n"; cin.getline(name2,arrayLength); cout<<"name1: "<<name1<<endl; cout<<"name2: "<<name2<<endl; cin.get(); return 0;}
分析:我們在輸入流中輸入name1 name2 name3,然后cin>>name1會讀取name1,因為name1后面是空格,但是空格符是保留的,因為在name2中讀取的結果是” name2 name3”。
get()方法:
get()的參數和使用方法與getline()方法一致,唯一的區別就是get()方法在碰到換行符是不對輸入流中的換行符進行刪除。這樣我們讀取輸入流的過程就會產生一個問題,怎么跳過換行符,幸運的是get()方法提供了一種變體,cin.get()讀取下一個字符,包括換行符,下面的例子掩飾了cin.get(name,size)和cin.get()的使用:
#include <iostream>using namespace std;int main(){ const int arrayLength = 40; char name1[arrayLength]; cout<<"Enter your name1:/n"; cin.get(name1,arrayLength); cin.get(); cout<<"name1: "<<name1<<endl; cin.get(); return 0;}運行結果:

getline()和get()方法讀取空行的問題:
所謂空行,就是輸入流中只有換行符,當getline()和get()方法碰到空行時,會設置失效位,使后面所有的輸入都中斷,我們分析下面的代碼:
#include <iostream>using namespace std;int main(){ const int arrayLength = 40; char name1[arrayLength]; char name2[arrayLength]; cout<<"Enter your name1:/n"; cin.get(name1,arrayLength); cout<<"Enter your name2:/n"; cin.get(name2,arrayLength); cout<<"name1: "<<name1<<endl; cout<<"name2: "<<name2<<endl; cin.get(); cin.get(); return 0;}比如我們輸入this is name1,回車,這時name1中讀取的是this is name1,接下來遇到回車就中斷了,在接下來name2讀取的時候輸入流就成為空行了,這就導致后面的cin.get()都沒有了效果,也就是上面程序總會一閃而過。因為get()方法碰到了中斷導致所有的輸入都中斷。碰都這種問題的解決方法是在讀取輸入流之前調用cin.clear()方法來恢復輸入。
#include <iostream>using namespace std;int main(){ const int arrayLength = 40; char name1[arrayLength]; char name2[arrayLength]; cout<<"Enter your name1:/n"; cin.get(name1,arrayLength); cout<<"Enter your name2:/n"; cin.get(name2,arrayLength); cout<<"name1: "<<name1<<endl; cout<<"name2: "<<name2<<endl; cin.clear(); cin.get(); cin.get(); return 0;}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用PHP能有所幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答
圖片精選