vc++中文本文件数据读取问题
已知.txt文件中数据格式如下:5172920007460.000026559806.6480.010431167954.069036031168.09740020434...
已知.txt文件中数据格式如下:
51729 2000 7 4 60.0000 26559806.648 0.0104311679 54.069036031 168.097400204 34.273492608 89.725355246 7.92e-022
如何做到一个一个数据的读取?
如将26559806.648赋值给a
将0.0104311679赋值给e
等等……
请高手指教 展开
51729 2000 7 4 60.0000 26559806.648 0.0104311679 54.069036031 168.097400204 34.273492608 89.725355246 7.92e-022
如何做到一个一个数据的读取?
如将26559806.648赋值给a
将0.0104311679赋值给e
等等……
请高手指教 展开
展开全部
给你提供了一个读取文件的函数ReadFile(),该函数可以将包含完整路径名的文件打开,读取其中以空格分隔的数据元素,并添加到动态数组vData中,源码如下:(不明白的地方可以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
#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
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询