std::basic_istream<CharT,Traits>::getline
来自 cppreference.cn
< 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。在构造和检查 sentry 对象之后,从 *this 提取字符,并将它们存储到数组的连续位置,该数组的第一个元素由 s 指向,直到发生以下任一情况(按显示的顺序测试)
- 输入序列中发生文件结束条件。
- 下一个可用字符 c 是定界符,由 Traits::eq(c, delim) 确定。定界符被提取(与
basic_istream::get()
不同)并计入 gcount(),但不存储。 - count 为非正数,或者已经提取了 count - 1 个字符(在这种情况下调用 setstate(failbit))。
如果函数没有提取任何字符,则在调用 setstate() 之前,会在本地错误状态中设置 failbit
。
在任何情况下,如果 count > 0,它会将空字符 CharT() 存储到数组的下一个连续位置,并更新 gcount()。
目录 |
[编辑] 注解
由于条件 #2 在条件 #3 之前测试,因此恰好适合缓冲区的输入行不会触发 failbit
。
由于终止字符被计为提取的字符,因此空输入行不会触发 failbit
。
[编辑] 参数
s | - | 指向用于存储字符的字符串的指针 |
count | - | 由 s 指向的字符串的大小 |
delim | - | 停止提取的定界字符。它被提取但不存储。 |
[编辑] 返回值
*this
[编辑] 异常
如果内部操作抛出异常,则会被捕获并设置 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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 531 | C++98 | std::getline 无法处理count 为非正数的情况 |
没有字符被 在这种情况下提取 |
[编辑] 参见
从 I/O 流中读取数据到字符串 (函数模板) | |
提取格式化数据 (公共成员函数) | |
提取字符 (公共成员函数) | |
提取字符块 (公共成员函数) |