C++ primer plus程序清单6.16

l_w_zeng 2016-07-14 09:16:42
大家好,我刚开始用c++ primer plus 中文版第五版学习c++,其中一个例程,书中的程序清单6.16,我打了这个代码之后每次读取txt文件时总是不能读取到最后一个数字,程序如下:
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE=60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream in_file;

cout<<"enter name of data file:";
cin.getline(filename,SIZE);
in_file.open(filename);
if(!in_file.is_open())
{
cout<<"could not open the file:";
cout<<"program terminating";
exit(EXIT_FAILURE);
}
double value;
double sum=0.0;
int count=0;

in_file>>value;
while(in_file.good() )
{
++count;
sum+=value;
in_file>>value;
}
if(in_file.eof()) cout<<"end of file reached.\n";
else if(in_file.fail()) cout<<"input terminated by data mismatch.\n";
else cout<<"input terminated for unknown reason.\n";
if(count==0) cout<<"NO data int the file";
else
{
cout<<"items read:"<<count<<endl;
cout<<"sum: "<<sum<<endl;
cout<<"Average: "<<sum/count<<endl;
}
in_file.close();
return 0;
}
txt文件内容及运行结果如图,总是没有读到最后一个数字,恳请知道答案的前辈指点一下,感激不尽

...全文
173 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
flying_music 2016-07-15
  • 打赏
  • 举报
回复
已经读到了啊,你算一下12个数的和是不是186,是你的count有问题,因为循环前已经读了一个数了,所以count应该从1开始
l_w_zeng 2016-07-15
  • 打赏
  • 举报
回复
引用 1 楼 cyfcsd 的回复:
已经读到了啊,你算一下12个数的和是不是186,是你的count有问题,因为循环前已经读了一个数了,所以count应该从1开始
谢谢你啦,昨晚可能是头脑犯晕了,弄错了,今天发现运行时正常的

65,187

社区成员

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

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