首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::getline

Defined in header <string>

template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim );

(1)

template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim );

(1)

(since C++11)

template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str );

(2)

template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str );

(2)

(since C++11)

getline从输入流中读取字符并将它们放入字符串:

1%29表现为UnformattedInputFunction,除了input.gcount()不受影响。在构造和检查Sentry对象之后,执行以下操作:

1%29次电话str.erase()

2%29提取字符input并将它们附加到str直到出现下列情况之一之前,%28已按所列顺序检查为%29

的文件结束条件为%29input在这种情况下,getlineeofbit...

B%29下一个可用的输入字符是delim,经Traits::eq(c, delim),在这种情况下,分隔符字符是从input,但没有附加到str...

C%29str.max_size()字符已被存储,在这种情况下getlinefailbit然后回来。

3%29如果由于任何原因没有提取字符%28---即使是丢弃的分隔符%29---getlinefailbit然后回来。

2%29getline(input, str, input.widen('\n'))即,默认分隔符是尾行字符。

参数

input

-

the stream to get data from

str

-

the string to put the data into

delim

-

the delimiter character

返回值

input...

注记

在空格分隔输入后立即使用时,例如在int n;std::cin>> n;,,,getline使用留在输入流上的尾行字符。运算符>>马上回来。一个常见的解决方案是忽略输入行中的所有剩余字符。cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');在切换到以线路为导向的输入之前。

下面的示例演示如何使用getline函数读取用户%27 s输入和如何逐行处理文件。

二次

代码语言:javascript
复制
#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";
}

二次

可能的产出:

二次

代码语言:javascript
复制
What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28

二次

另见

getline

extracts characters until the given character is found (public member function of std::basic_istream)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券