C++ Primer Plus 第六版第六章程序清单6.16(p195)出现的问题

按照书上的代码和输入输出的内容,是无法得到书上运行的答案的,那么问题出现在哪里呢?
先附上代码:

#include<iostream>
#include<fstream>//file I/O support
#include<cstdlib>//suport for exit()
using namespace std;

const int SIZE = 60;
int main()
{
	char fileName[SIZE];
	ifstream inFile;//对象,用于处理文件输入 
	cout << "Enter name of data file:" ;
	cin.getline(fileName, SIZE);
	inFile.open(fileName);//将inFile与文件关联 
	
	if(!inFile.is_open())//failed to open file
	{
		cout << "Could not open the file " << fileName << endl;
		cout << "Program terminating." << endl;
		exit(EXIT_FAILURE);
	}
	
	double value, sum=0.0;
	int count = 0;
	//这是第一种方法,从这里开始修改:
//	inFile >> value;//①这里直接把书上的这句删掉
	while(inFile.good())//while input good and no at EOF
	{
		++count;
//		sum += value;
//		②这里给书上的sum+=value和inFile >> value 换个位置,就可以得到和书上运行的一样的结果
		inFile >> value;
		sum += value;
	} 
	if(inFile.eof())
	{
		cout << "End of file reached." << endl;
	}
	else if(inFile.fail())
	{
		cout << "Input terminated by data mismatch." << endl;
	}
	else
	{
		cout << "Input terminated for unknown reason." << endl;
	}
	
	if(0==count)
	{
		cout << "No data processed." << endl;
	}
	else
	{
		cout << "Items read: " << count << endl
		<< "Sum: " << sum << endl
		<< "Average: " << sum/count << endl;
	}
	
	inFile.close();
	return 0;
}
 

其实第二种改法才是我自己debug想到的,我是在需要创建的文本文档中作了改动,因为debug发现按照书上的代码没有办法运行得到书上的结果,又想着书上能运行成功那么问题估计是不在代码,仔细看了一下代码,结合debug的结果,我在文本文档中加了个空格(按回车键有同效果)
在这里插入图片描述
不过第二种方法,在我一切工作完成之后(开心且嘚瑟了!!!)发现书上小字其实有提醒,有些文本编译器需要以回车和换行符结尾之类的吧啦吧啦……
emm不过人家说的是回车,我想的是空格……emm算是一种!创新了对不对!!!

这里主要记录第一种改发吧,是一位前辈跟我讲的哈哈哈哈他还说哪有人去改文档的,肯定是改代码啊……emm嘿嘿,涨姿势,记下来!
也希望后面遇到同样问题的人,迎刃而解鸭~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值