getline的两种定义
1.全局函数,在头文件 #include<string> 中,函数声明为:
- istream& getline ( istream& is, string& str, char delim )
- istream& getline ( istream& is, string& str )
2. istream的成员函数,函数声明为:
- istream& getline (char* s, streamsize n ) ; // char *s 表示 char类型的指针,也是char字符数组的首地址,将读取的内容
存入到 char类型的字符数组中
- istream& getline (char* s, streamsize n, char delim )
- istream的成员函数getline(),终止读取的条件,根据已读取的字符的个数来判定,实际上是读取n-1个字符,因为最后要为‘\0’留下一个位置。其他地方二者基本相同。
常用的是第一种,全局函数这种情况,getline函数的基本功能是 将流 istream& is 中的字符串存到string& str 当中去。
- 全局函数中两种声明的区别是第一种加了一个限定符号char delim,默认限定符号为‘\n’,即读到一个换行符就终止读取。
- 判断空行的办法是str.length()==0
- 判断输入结束的办法是is.eof()
函数声明
bool getline(istream &in, string &s)
功能说明:
从输入流读入一行到变量string s,即使是空格也可以读入。
–直到出现以下情况为止:
• 读入了文件结束标志
• 读到一个新行(有重载函数可以指定行分隔符,默认是"\n".)
• 达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束.
int main(int argc,char* argv[])
{
ifstream ifs;
ofstream ofs;
string str;
ifs.open(argv[1]);
ofs.open(argv[2]);
while(getline(ifs,str))
{
if(str.at(0)=='#')//过滤特殊的行(此处是#开头)
continue;
ofs<<str<<endl;
}
ifs.close();
ofs.close();
return 0;
}
C++依次读取文件中的字符串——getline()函数的应用
例如文件test.txt中有这么一段话:I am a boy. You are a girl.
如何一次一个的读取单词,即第一次读取I,第二次读取am,依次类推。
方法1:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream ifs("test.txt"); // 改成你要打开的文件
streambuf* old_buffer = cin.rdbuf(ifs.rdbuf());
string read;
while(cin >> read) // 逐词读取方法一
cout << read;
cin.rdbuf(old_buffer); // 修复buffer
}
方法2:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("test.txt"); // 改成你要打开的文件
ifs.unsetf(ios_base::skipws);
char c;
while(ifs.get(c)) // 逐词读取方法二
{
if(c == ' ')
continue;
else
cout.put(c);
}
}
方法3:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs("test.txt"); // 改成你要打开的文件
string read;
while(getline(ifs, read, ' ')) // 逐词读取方法三
{
cout << read << endl;
}
}
方法4:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream ifs("test.txt"); // 改成你要打开的文件
char buffer[256];
while(ifs.getline(buffer, 256, ' ')) // 逐词读取方法四
{
cout << buffer;
}
}
参考:
https://www.cnblogs.com/zhaojk2010/p/5727393.html
https://blog.csdn.net/yulijuanxmu/article/details/77936759