C++中std::getline函数的用法_极客玩家大白

std::getline

 

在头文件  中定义.

getline从输入流中读取字符, 并把它们转换成字符串.

1) 的行为就像UnformattedInputFunction, 除了input.gcount()不会受到影响.在构造和检查岗哨对象的, 执行以下操作:

1) 调用str.erase()

2) input并把它们添加到str的字符提取出来, 直到发生以下情况之一中列出的顺序进行检查

a) 上input文件结束的条件, 在这种情况下, getlineeofbit和回报.

b) 下一个可用的输入字符delim, Traits::eq(c, delim), 在这种情况下, 分隔符是从input提取进行了测试, 但不会追加到str.

c) str.max_size()字符, 在这种情况下, 已经被存储getlinefailbit并返回.

3) 如果没有字符提取任何理由(甚至没有被丢弃的分隔符), getlinefailbit, 并返回.

2) 同getline(input, str, input.widen(’\n’)), 默认的分隔符是’\n’字符.

参数

input - 流中获取数据 str - 把数据转换成字符串 delim - 分隔符

返回值

input

Notes

When used immediately after whitespace-delimited input, e.g. after int n; std::cin » n;, getline consumes the endline character left on the input stream by operator», and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits < std::streamsize >::max(), ’\n’); before switching to line-oriented input.

示例

下面的例子陈述了如何使用getline函数来读取用户输入, 以及如何按行处理文件内容. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <iostream>
#include <sstream>
 
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";
}

可能的输出:

1
2
3
4
What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28

版权声明


一个有故事的程序员

(转载本站文章请注明作者和出处 极客玩家大白

点击了解 :.NET技术人的网站


Show Disqus Comments

Post Directory