C++ getline函数用法详解


前言

当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取。


一、getline()函数的定义

(1)	
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
(2)	
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).

The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

Note that any content in str before the call is replaced by the newly extracted sequence.

Each extracted character is appended to the string as if its member push_back was called.

Parameters
is
istream object from which characters are extracted.
str
string object where the extracted line is stored.
The contents in the string before the call (if any) are discarded and replaced by the extracted line.

二、getline()函数的使用

1.可读取整行,包括前导和嵌入的空格,并将其存储在字符串对象中。

代码如下(示例):

// extract to string
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

2.char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为’\n’,也就是回车换行符(遇到回车停止读入)。

代码如下(示例):

getline(cin,line,'#');

表示遇到#停止读入


总结

我们可以使用stringstream来从一行英语we are the best!拆分成各个单词, 也可以使用getline()来获取某行的相关信息,还可以添加停止读入位。

本文作者:WeSiGJ

参考链接(包括但不限于):
http://c.biancheng.net/view/1345.html
https://www.cnblogs.com/overcode/p/4126799.html
http://www.cplusplus.com/reference/string/string/getline/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

WeSiGJ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值