为什么第2次打开文件会出错??

huyi2332 2009-05-19 10:02:24
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;

int main()
{
double pingjun(ifstream& in_stream,ofstream& out_stream);
void pfg(ifstream& in_stream,ofstream& out_stream,double pa);
double pj;
ifstream fin;
ofstream fout;
fin.open("d.dat");
if(fin.fail())
{
cout<<"input file opening failed"<<endl;
exit(1);
}
fout.open("d1.dat");
if(fout.fail())
{
cout<<"output file opening failed"<<endl;
}
pj=pingjun(fin,fout);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.precision(2);
cout<<"这些数字的平均数是"<<pj<<endl;
fin.close();
fin.open("d.dat");
if(fin.fail())
{
cout<<"input file opening failed"<<endl;
exit(1);
}
pfg(fin,fout,pj);
fin.close();
fout.close();
return 0;

}

double pingjun(ifstream& in_stream,ofstream& out_stream)
{
double next,sum=0;
int n=0;
while(in_stream>>next)
{
cout<<next<<endl;
sum=sum+next;
n++;
}
cout<<n<<" "<<sum<<endl;
double p_j;
p_j=(sum/n);
out_stream<<"平均数是"<<p_j<<endl;
return p_j;
}


这是源码
算平均数能算对,但是第2次打开D.DAT时却报错,求助高手!
...全文
94 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rainID 2009-05-20
  • 打赏
  • 举报
回复
共享模式,或者第二次打开之前,先关闭
hjjdebug 2009-05-20
  • 打赏
  • 举报
回复
fin.close(); 后fin 会处于一种错误状态,你可以用fin.rdstate(); 来查看。
用fin.clear(); 可以将流恢复为正常状态
lpf000 2009-05-20
  • 打赏
  • 举报
回复
第一次关闭后第二次打开前,清除错误状态,fin.clear();
nwao7890 2009-05-20
  • 打赏
  • 举报
回复
可能你没指定共享模式吧,查查open函数看怎么说的。
huyi2332 2009-05-20
  • 打赏
  • 举报
回复
void pfg(ifstream& in_stream,ofstream& out_stream,double pa)
{
double a,next;
while(in_stream>>next)
{
a=(next-pa)*(next-pa);
cout<<a<<endl;
out_stream<<a<<endl;
}
}
huyi2332 2009-05-19
  • 打赏
  • 举报
回复
D.DAT里的数据为浮点数~~
liliangbao 2009-05-19
  • 打赏
  • 举报
回复
帮顶先~

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧