首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++中std::getline()函数的用法

C++中std::getline()函数的用法

作者头像
Enjoy233
发布2019-03-05 14:56:04
7.2K0
发布2019-03-05 14:56:04
举报

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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年09月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • std::getline
  • 参数
  • 返回值
  • Notes
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档