ReadFile()

来源:互联网 发布:农村三级卫生服务网络 编辑:程序博客网 时间:2024/05/21 17:03

一个读取文件的函数ReadFile(),该函数可以将包含完整路径名的文件打开,读取其中以空格分隔的数据元素,并添加到动态数组vData中,你可以像普通数组一样去使用这个动态数组,如果你要获取动态数组的数据个数,可是使用int nSize = vData.size();源码如下:(不明白的地方可以hi我) #include<fstream> #include<iostream> #include<vector> #include<string> using namespace std; void ReadFile(vector<double> &vData, const char* pFilePath) { ifstream inFile; inFile.open(pFilePath); char ch; string buff; if(inFile.is_open()){ while(!inFile.eof()){ ch = inFile.get(); if(ch != ' ')buff.push_back(ch); // 以空格为分隔符 else { vData.push_back(atof(buff.c_str())); buff.clear(); } } inFile.close(); } } void main() // 测试 { vector<double> vData; const char* pFilePath = "c://a.txt"; // 文件路径 ReadFile(vData, pFilePath); vector<double>::iterator iter; cout << "The contents in " << pFilePath << " are:/n"; for(iter = vData.begin(); iter != vData.end(); ++iter)cout << *iter << endl; } 测试: C盘根目录下数据文件a.txt,其内容为:51729 2000 7 4 60.0000 26559806.648 0.0104311679 54.069036031 168.097400204 34.273492608 89.725355246 7.92e-022 运行,在屏幕中输出已经读到动态数组vData中的数据: The contents in c:/a.txt are: 51729 2000 7 4 60.0000 26559806.648 0.0104311679 54.069036031 168.097400204 34.273492608 89.725355246 7.92e-022 

原创粉丝点击