函數庫中的getline函數

原型

1、istream& getline ( istream &is , string &str , char delim );
2、istream& getline ( istream& , string& );

參數

is 進行讀入操作的輸入流
str 存儲讀入的內容
delim 終結符(其中第二個版本默認爲'\n')

返回值

與參數is一樣的輸入流


簡單的例子:
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    string temp;
    getline(cin, temp, ';');
    cout << temp << endl;
    getline(cin, temp, ';');
    cout << temp << endl;

    return 0;
}

輸入樣例一:
the first input                 
the second input; (第一個 ‘ ; ’)
the third input;      (第二個 '  ; ')
輸出:
the first input
the second input (遇到第一個‘ ; ’後輸出)
the third input

可見getline()會從cin流對象的緩存中不斷讀取字符到temp中直至遇到' ; ',這樣我們可以將一些cin原本會忽視的字符如tab,空格,換行符等讀進目標字符串;


輸入樣例二:
the first input;the second input
the third input;
輸出:
the first input  (遇到第一個' ; '後輸出)
the second input
the third input  (遇到第二個‘ ; ’後輸出)

這個例子也許能更好的說明getline()的實現原理。首先,當我們在鍵盤中輸入the first input;the second input時,cin對象會將其存放進緩衝區,然後由getline按照要求來逐個掃描緩衝區中的字符,當其掃描到the first input後面的‘ ; ’時便停止掃描,並將the first input寫進temp中。當第二次調用getline函數時,由於cin的緩衝區中仍然遺留之前輸入的the second input,因此getline會繼續從這裏開始掃描緩衝區直到再次遇到‘ ; ’,所以第二次輸出的temp會是 the second input (\n) the third input

要說明的一點是,這裏的getline與cin.getline沒有關係,它是<string>庫提供的成員函數,可以理解爲string類的友元函數。

PS:cin流輸入對象和cout流輸出對象其實並不像我們想象中的那麼簡單,其內部實現我至今仍沒有搞懂。希望有大神不吝賜教!



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