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>#
五、运行结果。