C++:如何读取文本数据?(2)

      程序语言 2006-9-23 21:02:00

利用C++文件流(fstream)从文本文件中读取数据的基本思想是:利用字符串(string)以整行的方式从文本文件中读取字符,然后通过的一定的标志如空格,逗号,分号等,将字符串分割成数据。这里可以利用sstream将字符串转换成数值。
————————————————————————————————
......

char ch[255],seprator;
string str1,str2;
int cnum;

......


cout<<"Please enter the well_data filename:";
cin>>filename;
filename=filename+".txt";
getwdata.open(filename.c_str());
if(!getwdata)
{
cout<<"Sorry I just can not find out the data file..."<<endl
<<"Press check the filename again..."<<endl;
system("pause");
exit(1);
}//文件打开失败处理
i=0;
while (getwdata.getline(ch,255))//获取整行数据
{
str1=ch;
if (str1.empty()) break; //如果本行数据为空,中断此次循环
str1=str1.substr(str1.find_first_not_of(" "));//去掉字符前面可能的空格
str2=str1[0];
cnum=1;
while (str1[cnum]!=seprator)//seprator 为分割符如空格,逗号等
{
str2=str2+str1[cnum];
cnum++;
}
s2float<<str2;
s2float>>wdepth0[i];
s2float.clear();
str2=str1[cnum+1];
cnum=cnum+2;
while (str1[cnum]!='\0')
{
str2=str2+str1[cnum];
cnum++;
}
s2float<<str2;
s2float>>wdata0[i];
s2float.clear();
//cout<<wdepth0[i]<<" "<<wdata0[i]<<endl;
i++;
}

......
————————————————————————————————

查看完全代码

 

标签集:TAGS:
回复Comments() 点击Count()
喜欢就顶一下

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}