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函数来读取用户输入, 以及如何按行处理文件内容.

#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";
}

可能的输出:

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.

The sum is 28
  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大白技术控

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值