名稱空間
變體
操作

std::getline

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
定義於標頭檔案 <string>
template< class CharT, class Traits, class Allocator >

std::basic_istream<CharT, Traits>&
    getline( std::basic_istream<CharT, Traits>& input,

             std::basic_string<CharT, Traits, Allocator>& str, CharT delim );
(1)
template< class CharT, class Traits, class Allocator >

std::basic_istream<CharT, Traits>&
    getline( std::basic_istream<CharT, Traits>&& input,

             std::basic_string<CharT, Traits, Allocator>& str, CharT delim );
(2) (C++11 起)
template< class CharT, class Traits, class Allocator >

std::basic_istream<CharT, Traits>&
    getline( std::basic_istream<CharT, Traits>& input,

             std::basic_string<CharT, Traits, Allocator>& str );
(3)
template< class CharT, class Traits, class Allocator >

std::basic_istream<CharT, Traits>&
    getline( std::basic_istream<CharT, Traits>&& input,

             std::basic_string<CharT, Traits, Allocator>& str );
(4) (C++11 起)

getline 從輸入流中讀取字元並將它們放入字串中

1,2) 行為類似於 UnformattedInputFunction,但 input.gcount() 不受影響。在構造並檢查哨兵物件後,執行以下操作:
1) 呼叫 str.erase()
2)input 提取字元並附加到 str,直到發生以下情況之一(按列出的順序檢查):
a) input 上的檔案結束條件,在這種情況下,getline 設定 eofbit
b) 下一個可用的輸入字元是 delim(透過 Traits::eq(c, delim) 測試),在這種情況下,從 input 提取分隔符字元,但不附加到 str
c) 已儲存 str.max_size() 個字元,在這種情況下,getline 設定 failbit 並返回。
3) 如果由於任何原因(甚至是被丟棄的分隔符)都沒有提取到字元,getline 設定 failbit 並返回。
3,4)getline(input, str, input.widen('\n')) 相同,即預設分隔符是換行符。

目錄

[編輯] 引數

input - 獲取資料的流
str - 存放資料的字串
delim - 分隔符字元

[編輯] 返回值

input

[編輯] 注意事項

當消費空白分隔的輸入時(例如 int n; std::cin >> n;),任何跟隨的空白,包括換行符,都將留在輸入流中。然後,當切換到面向行的輸入時,使用 getline 檢索的第一行將只是該空白。在可能不希望出現此行為的情況下,可能的解決方案包括:

[編輯] 示例

以下示例演示瞭如何使用 getline 函式讀取使用者輸入,以及如何逐行或透過 delim 引數按行的一部分處理流。

#include <iostream>
#include <sstream>
#include <string>
 
int main()
{
    // greet the user
    std::string name;
    std::cout << "What is your name? ";
    std::getline(std::cin, name);
    std::cout << "Hello " << name << ", nice to meet you.\n";
 
    // read file line by line
    std::istringstream input;
    input.str("1\n2\n3\n4\n5\n6\n7\n");
    int sum = 0;
    for (std::string line; std::getline(input, line);)
        sum += std::stoi(line);
    std::cout << "\nThe sum is " << sum << ".\n\n";
 
    // use separator to read parts of the line
    std::istringstream input2;
    input2.str("a;b;c;d");
    for (std::string line; std::getline(input2, line, ';');)
        std::cout << line << '\n';
}

可能的輸出

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28.
 
a
b
c
d

[編輯] 缺陷報告

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

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 91 C++98 getline 不作為非格式化輸入函式 作為非格式化輸入函式

[編輯] 參見

提取字元直到找到給定字元
(std::basic_istream<CharT,Traits> 的公共成員函式) [編輯]