std::getline
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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) 调用
str.erase()2) 从
input 提取字符并后附它们到 str,直到满足下列任一条件(按顺序检查):b) 下个可用输入字符是
delim,以 Traits::eq(c, delim) 进行检测,此时从 input 提取分隔字符,但不后附它到 str。2) 同
getline(input, str, input.widen('\n')),即默认分隔符是换行符。参数
| input | - | 获取数据来源的流 |
| str | - | 放置数据的目标字符串 |
| delim | - | 分隔字符 |
返回值
input
注解
消耗空白符分隔的输入(例如 int n; std::cin >> n;)时,任何后随的空白符,包括换行符都会被留在流中。然后当切换到面向行的输入时,以 getline 取得的首行只会是该空白符。多数情况下这是不想要的行为,可能的解法包括:
- 对
getline的显式的额外初始调用 - 以
std::cin >> std::ws移除额外的空白符 - 以
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');忽略输入行上剩下的全部字符
示例
下列代码演示如何用 getline 函数读取用户输入以及如何逐行处理文件。
运行此代码
#include <iostream>
#include <sstream>
#include <string>
int main()
{
// 问候用户
std::string name;
std::cout << "你的名字是?";
std::getline(std::cin, name);
std::cout << "你好 " << name << ",很高兴见到你。\n";
// 逐行读文件
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 << "\n总和是 " << sum << "。\n";
// 使用分隔符读取文本行的各部分
std::istringstream input2;
input2.str("a;b;c;d");
for (std::string line; std::getline(input2, line, ';'); )
std::cout << line << '\n';
}
可能的输出:
你的名字是?John Q. Public
你好 John Q. Public,很高兴见到你。
总和是 28。
a
b
c
d
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 91 | C++98 | getline 没有表现为无格式输入函数
|
表现为有格式输入函数 |
参阅
| 持续提取字符,直到找到给定字符 ( std::basic_istream<CharT,Traits> 的公开成员函数)
|