读书人

c++中怎么利用vector fstream进行文件

发布时间: 2012-12-23 11:28:15 作者: rapoo

c++中如何利用vector fstream进行文件的读取

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

int filetovector(string filename,vector<string>& sevc)
{
ifstream infile(filename.c_str());
if(!infile)
return 1;
string s;
while (getline(infile,s))
sevc.push_back(s);

infile.close(); //--关闭文件
if (infile.eof()) //--遇到文件结束符
return 4;
if(infile.bad()) //-- 发生系统故障
return 2;
if(infile.fail()) //读入数据失败
return 3;
}
int t_main(int argc, char *argv[])
{

vector<string> sevc;
string filename,s;

//读入文件名
cout<<"Entet the FileName :";
cin>>filename;

//处理文件
switch(filetovector(filename,sevc))
{
case 1:
cout<<"error:can't open file:"
<<filename<<endl;

return -1;
case 2:
cout<<"error:system failure"<<endl;
return-1;
case 3:
cout<<"error:read failure"<<endl;
return -1;
default:
return 1;
}

//使用istringstream从vector里每次读取一个单词的形式读取所存储的行
istringstream isstream;

for(vector<string>::iterator iter=sevc.begin();iter!=sevc.end();++iter)
{
isstream.str(*iter);
while (isstream>>s)
{
cout<<s<<endl;
}
isstream.clear(); //--将istringstream流设置为有效状态
}
return 0;
}

getline()是按行读取的,

isstream>>s 从流中读取字符串到s 注意 此时流中字符串是以行存储的当读到s中的时候遇到空格就结束读取(开头的空格不算),然后循环读取下空格下一个位置的字符串

读书人网 >C++

热点推荐