名稱空間
變體
操作

std::basic_istream<CharT,Traits>::getline

來自 cppreference.com
< cpp‎ | io‎ | basic istream
 
 
 
 
basic_istream& getline( char_type* s, std::streamsize count );
(1)
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );
(2)

從流中提取字元直到行尾或指定的定界符 delim

第一個過載等價於 getline(s, count, widen('\n'))

行為如同 UnformattedInputFunction。在構造並檢查哨兵物件後,從 *this 中提取字元並存儲到 s 指向的陣列的連續位置中,直到以下任何一個情況發生(按所示順序測試):

  1. 輸入序列中出現檔案結束條件。
  2. 下一個可用字元 c 是定界符,由 Traits::eq(c, delim) 確定。定界符被提取(與 basic_istream::get() 不同)並計入 gcount(),但不儲存。
  3. count 為非正數,或已提取 count - 1 個字元(在這種情況下會呼叫 setstate(failbit))。

如果函式未提取任何字元,則在呼叫 setstate() 之前,區域性錯誤狀態中會設定 `failbit`。

在任何情況下,如果 count > 0,它會將空字元 CharT() 儲存到陣列的下一個連續位置並更新 gcount()

目錄

[編輯] 注意

因為條件 #2 在條件 #3 之前測試,所以正好適合緩衝區大小的輸入行不會觸發 failbit

因為終止字元被算作提取的字元,所以空輸入行不會觸發 failbit

[編輯] 引數

s - 指向儲存字元的字串的指標
count - s 指向的字串的大小
delim - 停止提取的定界字元。它會被提取但不儲存。

[編輯] 返回值

*this

[編輯] 異常

如果發生錯誤(錯誤狀態標誌不是 goodbit)並且 exceptions() 被設定為丟擲該狀態的異常,則丟擲 failure

如果內部操作丟擲異常,則會被捕獲並設定 badbit。如果 exceptions()badbit 設定,則重新丟擲異常。

[編輯] 示例

#include <array>
#include <iostream>
#include <sstream>
#include <vector>
 
int main()
{
    std::istringstream input("abc|def|gh");
    std::vector<std::array<char, 4>> v;
 
    // note: the following loop terminates when std::ios_base::operator bool()
    // on the stream returned from getline() returns false
    for (std::array<char, 4> a; input.getline(&a[0], 4, '|');)
        v.push_back(a);
 
    for (auto& a : v)
        std::cout << &a[0] << '\n';
}

輸出

abc
def
gh

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 531 C++98 std::getline 無法處理
count 為非正數的情況
在這種情況下沒有字元被
提取

[編輯] 另請參閱

從 I/O 流讀取資料到字串
(函式模板) [編輯]
提取格式化資料
(public 成員函式) [編輯]
提取字元
(public 成員函式) [編輯]
提取字元塊
(public 成員函式) [編輯]