c++中怎么用一个函数读取不同的文件??!!

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
typedef vector<vector< double> > Mat;
Mat input();
int main (void)
{
Mat a = input();//读取文件函数
for (int i = 0; i < a.size();i++)//输出shuju.txtz中的数据
{
for(int j = 0; j < a[i].size();j++)
{
cout<<fixed<<a[i][j]<<" "<<flush;
}
cout<<endl;
}
return 0;
}
Mat input()//读取文件函数
{
ifstream in("shuju.txt");
Mat a;
istringstream istr;
string str;
vector<double> tmpvec;
while(getline(in,str))
{
istr.str(str);
double tmp;
while(istr>>tmp)
{
tmpvec.push_back(tmp);
}
a.push_back(tmpvec);
tmpvec.clear();
istr.clear();
}
in.close();
return a;
}
我要是在程序的其它地方读取其他文件比如shuju1.txt的话又要重新建立个函数,这样很麻烦。能有其他办法不???!!!

使用vector<string> FileList,存下每一个文件的名字和路径,比如D:\\001.txt,或者002.txt,类似的所有文件名,然后读取文件时使用for来遍历Filelist,每一次可以使用类似 fopen(Filelist[i])来打开一个文件来进行读取,如此,就可以对你要读的文件全部读取了。至于读进来的东西存在哪里是你自己要想的事情。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-08
读取的文件的所在路径放在一个容器中, 遍历容器,依次读取
相似回答