C++依次读取文件中的字符串——getline()函数的应用

来源:互联网 发布:电子版报纸制作软件 编辑:程序博客网 时间:2024/06/03 06:24

1.全局getline函数

getlime()有着两种形式http://www.cplusplus.com/reference/string/string/getline/
(1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);

其中
getline(istream &in, string &s)

从输入流读入一行到string s

•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束

#include <iostream>  #include <fstream>  #include <string>  using namespace std;  int main()  {    ifstream ifs("test.txt");      // 改成你要打开的文件    string read;    while(getline(ifs, read, ' ')) // 逐词读取方法三    {      cout << read << endl;    }  }  

参考
http://blog.csdn.net/sibo626/article/details/6781036

2.流的成员函数

http://www.cplusplus.com/reference/istream/istream/getline/

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

注意这个是cha*

一个例子http://www.cnblogs.com/JCSU/articles/1190685.html

0 0