如何用c++读取文本文件到结构体数组中

文件格式如下,包含整数,逗号,日期和时间的字符串,要求过滤掉逗号和换行符
6,2013-07-22,15-27-06
54,2013-07-22,15-35-12
13,2013-07-22,15-37-12
13,2013-07-22,15-39-12
12,2013-07-22,15-41-12
46,2013-07-22,15-43-12
13,2013-07-22,15-45-12
19,2013-07-22,15-47-12
19,2013-07-22,15-49-12
55,2013-07-22,15-51-12
64,2013-07-22,15-53-12
62,2013-07-22,15-55-12
67,2013-07-22,15-57-12
结构体有三个变量,分别存储三个数据

用 C 语言的方法很容易对付。
窍门:if ( fscanf(fp,"%d,%[^,],%s",&s[n].n,s[n].y,s[n].t)==3) n++;
#include <iostream>
#include<stdio.h>
using namespace std;
struct S{
int n;
char y[12];
char t[12];
};

main()
{
struct S s[500]; // 假定数据不超过 500 行
FILE *fp;
int i,n=0;
fp=fopen("abc.txt","r");
while(1){
if ( fscanf(fp,"%d,%[^,],%s",&s[n].n,s[n].y,s[n].t)==3) n++;
if (feof(fp))break;
};
fclose(fp);
printf("n=%d\n",n);
for (i=0;i<n;i++) printf("%d %s %s\n",s[i].n,s[i].y,s[i].t);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-30
结构里写个解析函数不久搞定了呀
1 把 1个string (按逗号)分割成3个STRING对应你结构里的变量
2 分别解析这些string 转换成变量
第2个回答  2013-07-31
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
 
struct Data 
{
int id;
string date;
string time;
};
 
ostream& operator<<(ostream& a,Data& d)
{
a<<d.id<<"\t"<<d.date<<"\t"<<d.time<<endl;
return a;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
ifstream in(".\\data.txt");
vector<Data> data_vec;
 
string strLine;
istringstream istr;
string temp;
while (!in.eof())
{
getline(in,strLine);
istr.str(strLine);
 
Data da;
getline(istr,temp,',');
da.id=atoi(temp.c_str());
getline(istr,temp,',');
da.date=temp;
getline(istr,temp,',');
da.time=temp;
 
data_vec.push_back(da);
istr.clear();
}
 
for (int i=0;i<data_vec.size();i++)
{
cout<<data_vec.at(i);
}
cin.get();
return 0;
}

相似回答