std::getline
来自 cppreference.cn
< cpp | 字符串 | basic string
定义于头文件 <string> |
||
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(2) | (自 C++11 起) |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(3) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(4) | (自 C++11 起) |
getline
从输入流读取字符并将它们放入字符串中
1) 调用
str.erase()
。2) 从
input
提取字符并将它们追加到 str
,直到发生下列情况之一(按列出顺序检查)b) 下一个可用的输入字符是
delim
,由 Traits::eq(c, delim)
测试,在这种情况下,分隔符字符从 input
中提取,但不追加到 str
。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> 的公共成员函数) |