编写函数打开文件用于输入,将文件内容读入string类型的Vector容器,每一行存储为该容器对象的一个元素
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int fileToVector(string fileName, vector<string> &svec)
{
ifstream inFile(fileName.c_str());
if(!inFile)
{
return 1;
}
string s;
while(getline(inFile, s))
svec.push_back(s);
inFile.close();
if(inFile.eof())
return 4;
if(inFile.bad())
return 3;
if(inFile.fail())
return 2;
}
int main()
{
string fileName, s;
vector<string> svec;
cout << "Enter file name; " << endl;
cin >> fileName;
switch(fileToVector(fileName, svec))
{
case 1:
cout << "error: can not open file" << fileName << endl;
return -1;
case 2:
cout << "error: read failure" << endl;
return -1;
case 3:
cout << "error: system failure" << endl;
return -1;
}
cout << "Vector:" << endl;
for (vector<string>::const_iterator it = svec.begin(); it != svec.end(); ++it)
cout << *it << endl;
return 0;
}
浙公网安备 33010602011771号