std::getline
来自 cppreference.cn
< cpp | string | 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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 91 | C++98 | getline 不作为非格式化输入函数 |
作为非格式化输入函数 |
[编辑] 参见
提取字符直到找到给定字符 ( std::basic_istream<CharT,Traits> 的公共成员函数) |