有一个dat的文件,里面的内容是:
Earth: 6928198253 9.81
Jenny's World: 32155648 8.93
Tramtor: 89000000000 15.03
Trellan: 5214000 9.62
Freestone: 3945851000 8.68
Taanagoot: 361000004 10.23
Marin: 252409 9.79
用下面的代码,为什么会出错?错在哪里,请高手们帮一下,谢谢。
#include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdlib>
const int LIM=20;
struct planet
{
char name[LIM];
double population;
double g;
};
const char *file="planet.dat";
inline void eatline(){while(std::cin.get()!='\n') continue;}
int main()
{
using namespace std;
planet p1;
cout<<fixed;
fstream finout;
finout.open(file,ios_base::in|ios_base::out|ios_base::binary);
int ct=0;
if(finout.is_open())
{
finout.seekg(0);
cout<<"Here are the current contents of the "<<file<<" file:\n";
while(finout.read((char *) &p1,sizeof p1))
{
cout<<ct++<<": "<<setw(LIM)<<p1.name<<":02 "<<setprecision(0)
<<setw(12)<<p1.population<<setprecision(2)<<setw(6)
<<p1.g<<endl;
}
if(finout.eof())
finout.clear();
else
{
cerr<<"Error in reading "<<file<<".\n";
exit(EXIT_FAILURE);
}
}
else
{
cerr<<file<<" coule not be opened--bye.\n";
exit(EXIT_FAILURE);
}
cout<<"Enter the recond number you wish to change:";
long rec;
cin>>rec;
eatline();
if(rec<0||rec>=ct)
{
cerr<<"Invalid record number--bye\n";
exit(EXIT_FAILURE);
}
streampos place=rec * sizeof p1;
if(finout.fail())
{
cerr<<"Error on attempted seek\n";
exit(EXIT_FAILURE);
}
finout.read((char *) &p1,sizeof p1);
cout<<"Your selection:\n";
cout<<rec<<": "<<setw(LIM)<<p1.name<<"; "<<setprecision(0)<<setw(12)<<p1.population<<setprecision(2)<<setw(6)<<p1.g<<endl;
if(finout.eof())
finout.clear();
cout<<"Enter planet name:";
cin.get(p1.name,LIM);
eatline();
cout<<"Enter planetary population:";
cin>>p1.population;
cout<<"Enter planet's acceleration of gravity:";
cin>>p1.g;
finout.seekp(place);
finout.write((char *) &p1,sizeof p1)<<flush;
if(finout.fail())
{
cerr<<"Error on attempted write\n";
exit(EXIT_FAILURE);
}
ct=0;
finout.seekg(0);
cout<<"Here are the new contents of the "<<file<<" file:\n";
while(finout.read((char *) &p1,sizeof(p1)))
{
cout<<ct++<<": "<<setw(LIM)<<p1.name<<": "<<setprecision(0)<<setw(12)<<p1.population<<setprecision(2)<<setw(6)<<p1.g<<endl;
}
finout.close();
cout<<"Done.\n";
return 0;
}
如何改?
追答思路是可以先读一行进buffer
对buffer 取:前面的进姓名 :和最后的空格之间的用atoi转换;空格之后的需要转成double
然后循环处理下一行