2021-01-16 C++标准库getline函数的使用

                    C++ 标准库getline函数的使用

一、头文件:#include <string>

二、getline函数有四种重载形式。

istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

istream &is 表示一个输入流,譬如cin;
string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);
char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。

三、函数功能说明:从输入流读入一行到变量string s,及时是空格也可以读入。

      –直到出现以下情况为止:
      •读入了文件结束标志
      •读到一个新行(有重载函数可以指定行分隔符,默认是"\n".)
      •达到字符串的最大长度
      –如果getline没有读入字符,将返回false,可用于判断文件是否结束.

四、实例测试。

   getline.cpp

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
  ifstream fin,fin2;
  fin.open("file.txt");
  fin2.open("file2.txt");
  
  if (!fin)//检查文件打开是否成功
  {
		return  1;
  }
  if (!fin2)//检查文件打开是否成功
  {
		return  1;
  }
  
  string str,str2,str_input;
  
  getline(cin, str_input, 'A');
  cout<<"The string we have gotten is :"<<str_input<<'.'<<endl;
  
  cout<<"getline(fin,str)"<<endl;
  while(getline(fin,str))
  {
     cout<<str<<endl;
  }
  
  cout<<"\r\n\r\n\r\n"<<endl;
  cout<<"while(getline(fin2,str2,'#'))"<<endl;
  while(getline(fin2,str2,'#'))
  {
     cout<<str2<<endl;
  }
  fin.close();
  fin2.close();
  return 0;
}

file.txt

mple line 0</span>
<tag>Example line 1</tag>
<span>Example line 1.5</span>
<tag>
Example# line 2
</tag>
Example line 3
<span>Example line 4</span>

file2.txt

mple line A0</span>#
<tag>Example line 1</tag>#
<span>Example line 1.5</span>#
<tag>#
Example# Aline 2#
</tag>#
Example line 3#
<span>Example line 4</span>#

五、运行结果。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值