65,211
社区成员
发帖
与我相关
我的任务
分享#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
int main()
{
int fileToVector(string fileName,vector<string>&svec);
vector<string> svec;
string fileName,s;
//读入文件名
cout<<"Enter filename:"<<endl;
cin>>fileName;
//处理文件
switch(fileToVector(fileName,svec))
{
case 4:
cout<<"error:can not open file:"<<fileName<<endl;
return -1;
case 2:
cout<<"error:system failure:"<<endl;
return -1;
case 3:
cout<<"error:read failure"<<endl;
return 1;
}
//使用istringstream从vector里每次读一个单词的形式读取所存储的行
string word;
istringstream isstream;
for(vector<string>::iterator iter=svec.begin();iter!=svec.end();iter++)
//将vector对象的当前元素复制给istringstream对象
isstream.str(*iter);
//从istringstream对象中读取单词并输出
while(isstream>>word)
{
cout<<word<<endl;
}
isstream.clear();
return 0;
}
int fileToVector(string fileName,vector<string>&svec)
{
//创建ifstream对象infile并绑定到由形参fileName指定的文件名
ifstream infile(fileName.c_str());
if(!infile)//打开文件失败
return 1;
//将文件内容读入到string类型的vector容器
//每一行存储为该容器对的一个元素
string s;
while(getline(infile,s))
svec.push_back(s);
infile.close();//关闭文件
if(infile.eof())//遇到文件结束符
return 4;
if(infile.bad())//发生系统鼓掌
return 2;
if(infile.fail())//读入数据失败
return 3;
}