读书人

问个简单的文本读取的有关问题

发布时间: 2012-03-02 14:40:29 作者: rapoo

问个简单的文本读取的问题!
文件名:streetline.dat
数据例子:
"1 ", "虬江路 ",761.356,2, " "7986.792482,7907.299315,7996.711757,8668.590661 "
"3 ", " ",431.075,4, " "6626.485838,7812.885253,6662.512206,7862.576661,6674.717772,7889.278321,6816.208421,8198.811821 "
"4 ", "黑山路 ",0.901,2, " "5039.072572,7694.206706,5039.383299,7693.360838 "
"5 ", "国庠路 ",0.740,2, " "4448.981549,7485.290372,4449.224122,7484.590819 "
现在想实现这样一个功能读取每条记录到变量里,第一个为编号,二个为名称,第三个为长度,第四个字段表示后面共有多少个点,后面的为坐标点.
不知道该怎么写,自己写了个但是不对.请人指教
这是我写的
void transfile()
{
char chA;
char* streetno;
char* streetname;
double* streetlen;
int* pointnum;
double** pointns;
ifstream infilestreet( "streetline.dat ");
if(!infilestreet)
{
cout < < "Cannot open streetline.dat file! " < <endl;
}

int filenum = 0;

streetno = (char*) malloc( filenum*sizeof(char) );
streetname = (char*) malloc( filenum*sizeof(char) );
streetlen = (double*) malloc( filenum*sizeof(double) );
pointnum = (int*) malloc( filenum*sizeof(int) );
pointns = (double**) malloc( filenum*sizeof(double));


while(!infilestreet.eof())
{
infilestreet> > streetno[filenum]> > chA> > streetname[filenum]> > chA> > streetlen[filenum]> > chA> > pointnum[filenum];
for(int z=0;z <2*pointnum[filenum]-1;z++)
{
infilestreet> > pointns[filenum][z]> > chA;
}
filenum++;
}
infilestreet.close();
filenum--;

streetno = (char*) realloc(streetno,(filenum)*sizeof(char));
streetname = (char*) realloc(streetname,(filenum)*sizeof(char));
streetlen = (double*) realloc(streetlen,(filenum)*sizeof(double));
pointnum = (int*) realloc(pointnum,(filenum)*sizeof(int));
pointns = (double**) realloc(pointns,(filenum)*sizeof(double));
}



[解决办法]
#include <fstream>
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
ifstream openf( "test.txt ");
if(openf.fail())cerr < < "error in openning file! " < <endl;
else
{
int id, npoint;
char name[20]={0}, info[80]={0};
float len;

char tmp;
openf> > tmp> > id;
openf> > tmp> > tmp> > tmp;
openf.get(name, 20, '\ " ');
openf> > tmp> > tmp> > len;
openf> > tmp> > npoint;
openf> > tmp> > tmp> > tmp;
openf.get(info, 80, '\ " ');

//output:
cout < <id < < "\t " < <name < < "\t " < <endl
< <npoint < < " Point(s): " < <info < <endl < <endl;

}

system( "pause ");
return 0;
}

/*
test.txt 文件测试, 内容:
"4 ", "黑山路 ",0.901,2, " "5039.072572,7694.206706,5039.383299,7693.360838 "


"5 ", "国庠路 ",0.740,2, " "4448.981549,7485.290372,4449.224122,7484.590819 "

程序仅处理第一行,
后面的内容类似处理就是了,
也可以考虑使用 stringstream
*/

读书人网 >C++

热点推荐