按照书上的代码和输入输出的内容,是无法得到书上运行的答案的,那么问题出现在哪里呢?
先附上代码:
#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嘿嘿,涨姿势,记下来!
也希望后面遇到同样问题的人,迎刃而解鸭~