ReadFile()

一个读取文件的函数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 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值