命名空间
变体
操作

std::getline

来自 cppreference.cn
< 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> 的公共成员函数) [编辑]