可以编译,可结果出错,大家帮忙看一下

wind1985_1011 2007-06-24 10:23:33
这是C++ primer书中的一个例子

text.txt中的内容为:
abcd
efg
hi
j

代码运行后text.txt中的内容修改为
abcd
efg
hi
j
5 9 12 14
程序的功能为,在文件的末尾写一个新行,该行包含每一行开头的相对位置。
我的调试环境为DEC++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream inout("text.txt",fstream::ate |fstream::in |fstream::out);
if(!inout)
{
cerr<<" Unable to open the file !"<<endl;
system("pause");
return -1;
}

ifstream::pos_type end_mark =inout.tellg();
inout.seekg(0,fstream::beg);
int cnt =0;
string line;

while(inout && inout.tellg() !=end_mark
&& getline(inout,line))
{
cnt=cnt+line.size()+1;

ifstream::pos_type mark = inout.tellg();
inout.seekp(0,fstream::end);
inout<<cnt;

if(mark !=end_mark) inout<<" ";
inout.seekg(mark);
}

inout.clear();
inout.seekp(0,fstream::end);
inout<<"\n";
system("pause");
return 0;
}
...全文
221 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
songzhenqiu 2007-06-25
  • 打赏
  • 举报
回复
在vc中将while(inout && inout.tellg() !=end_mark
&& getline(inout,line))
改为while(inout.good() && inout.tellg() !=end_mark
&& getline(inout,line))
可以得出结果。
在dev中没有试验。
juicee 2007-06-25
  • 打赏
  • 举报
回复
LZ你的运行结果呢?
wind1985_1011 2007-06-25
  • 打赏
  • 举报
回复
程序不会终止运行

64,651

社区成员

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

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