为什么关闭文件后再打开就出现错误?

chinagao 2008-09-02 03:34:47
在打开文件"1.TXT".其中的内容是"1、2、3、4、5"
程序的目的是:读取文本的中间数.如果文本的数字是奇数(如上),则中间数是:3.
如果是偶数则是3和4的平均数(如1、2 3 4 5 6)中间数就是3.5.
写的代码如下:
运行后宣示:在打开文件失败!什么原因?(input the file is fail(2))
#include <iostream>
#include <fstram>
#include <cstdlib>
using namespace std;

int main()
{
int next,count,t;

ifstream fin;
ofstream fout;

fin.open("1.txt");
if(fin.fail())
{cout <<"input the file is fail(1)."<<endl;
//exit(1);
}

while(fin>>next)
{
count++;
}
fin.close();
if(count%2!=0)
{
fin.open("1.txt");
if(fin.fail())
{cout << "input the file is fail(2)";
//exit(1);
}
fout.open("2.txt");
if(fout.fail())
{
cout <<"output the file is fail(3)";
//exit(1);
}

t=(next+1)/2
cout << "the median is :" <<t;
fout << "the median is :" <<t;

return 0;
}
...全文
117 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
太乙 2008-09-02
  • 打赏
  • 举报
回复


#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

void main()
{
int next[100],count=0,t;

ifstream fin;
ofstream fout;

fin.open("1.txt");
if(fin.fail())
{
cout <<"input the file is fail(1)." <<endl;
fin.close();
return;
}
while(fin>>next[count])
{
count++;
}
fin.close();
fin.clear();

fout.open("2.txt");
if(fout.fail())
{
cout <<"output the file is fail(3)";
fout.close();
return;
}
if (count%2)//奇数
{
t=next[count/2];

}
else
{
t=next[(count-1)/2]+next[(count+1)/2];
t/=2;
}
cout << "the median is :" <<t;
fout << "the median is :" <<t;
fount.close();
return;
}

fibbery 2008-09-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 chinagao 的回复:]
呵呵!
fin.clear()是起什么作用?
[/Quote]
复位文件流的标志,包括bad、eof等
太乙 2008-09-02
  • 打赏
  • 举报
回复
汗~~lz这代码??
fibbery 2008-09-02
  • 打赏
  • 举报
回复
关闭之后,需要使用clear将标志复位,否则任何操作都无效!就是说,不能够再次利用了,不能再open其他文件。
chinagao 2008-09-02
  • 打赏
  • 举报
回复
呵呵!
fin.clear()是起什么作用?
fibbery 2008-09-02
  • 打赏
  • 举报
回复
关闭之后,需要使用clear将标志复位,否则任何操作都无效!
tengye19840704 2008-09-02
  • 打赏
  • 举报
回复
你这个能运行的?
头文件都错了
t=(next+1)/2
这个后面还少;号
太乙 2008-09-02
  • 打赏
  • 举报
回复
fin.close();

后面加上

fin.clear();
试试
太乙 2008-09-02
  • 打赏
  • 举报
回复
lz普通话不咋好?是不?

64,639

社区成员

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

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