C++ Prime P255 本来是学习该页的用 vector<string> files
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
void main()
{
ifstream input;
string s,filename = "c:/ludashi.txt";
vector<string> files;
files.push_back(filename);
vector<string>::const_iterator it = files.begin();
while (it!=files.end()) {
input.open(filename.c_str());
if(!input)break;
while(input>>s)cout<<s<<endl;
input.close();
input.clear();
++it;
}
}
自己捣鼓了一个用getline 读文件:
getline此时的用法 直接 getline(ifile,s)
ifile: 读文件的流,即ifstream对象
s: string 对象
// 标准IO库.cpp
//P253
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream& readfilebyline(ifstream& in){
string s;
if(!in)exit(EXIT_FAILURE);// 流出错
while(getline(in,s))
cout<<s<<endl;
in.close();
in.clear();
return in;
}
void main()
{
string filename = "c:/ludashi.txt";
ifstream ifile(filename.c_str());
if(ifile.is_open())
readfilebyline(ifile);
}
参考 http://wenku.baidu.com/view/590cce0abb68a98271fefaf4.html
中的第四条:
getline(cin,s) ; // 就是把输入的一行赋予字符串s, 把cin换成ifstream的文件流ifile 即可.
因为 ifstream 由 istream 派生而来....继承了其中的方法getline,因此用法雷同.
另外可以参考:
http://www.cnblogs.com/kevin2010_vip/archive/2010/02/03/1662853.html
// 如果是这样,则遇到空格就算读了一次
ifstream& readfilebyline(ifstream& in){
string s;
while(in>>s)cout<<s<<endl;
return in;
}
运行结果是 原txt文件中的第一行没有, 原因估计是 在 mian() 中给ifile(filename.c_str()) 是就读过了 ?
//---
再改,直接在main () 中, 第一行还是没有读到,奇怪了.如下:
// 再改改 : 直接在 main中 用getline 就可以把第一行读出: