Namespaces
Variants

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

From cppreference.net
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

异常

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

如果内部操作抛出异常,该异常会被捕获并设置 badbit 。如果为 badbit 设置了 exceptions() ,则异常会被重新抛出。

示例

#include <array>
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
    std::istringstream input("abc|def|gh");
    std::vector<std::array<char, 4>> v;
    // 注意:以下循环在 getline() 返回的流上调用 std::ios_base::operator bool() 返回 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流读取数据到字符串
(函数模板)
提取格式化数据
(公开成员函数)
提取字符
(公开成员函数)
提取字符块
(公开成员函数)