命名空间
变体
操作

std::getline

来自 cppreference.cn
 
 
 
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
  • 使用 std::cin >> std::ws 删除连续的空白字符。
  • 使用 cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); 忽略输入行上所有剩余的字符。

[编辑] 示例

以下示例演示如何使用 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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 91 C++98 getline 的行为不像未格式化输入函数 行为如同未格式化输入函数

[编辑] 参见

提取字符直到找到给定字符
std::basic_istream<CharT,Traits> 的公共成员函数) [编辑]