首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

ifstream有关问题

2013-12-07 
ifstream问题代码如下#include iostream#include fstream#include cstdlibusing namespace stdcons

ifstream问题
代码如下

#include <iostream>
#include <fstream>
#include <cstdlib>

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);
if(!inFile.is_open())
{
cout<<"could not open the file "<<filename<<endl;
cout<<"Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;

inFile>>value;
while(inFile.good())
{
++count;
sum += value;
inFile>>value;
}
if(inFile.eof())
{
cout<<"End of the file.\n";
}
else if(inFile.fail())
{
cout<<"Input terminated by data mismatch.\n";
}
if(count == 0)
{
cout<<"No data processed.\n";
}
else
{
cout<<"Items read:"<<count<<endl;
cout<<"Sum:"<<sum<<endl;
cout<<"Average:"<<sum/count<<endl;
}

inFile.close();
return 0;
}

主要部分已经用红色标出,

我自己建了个txt文档,在里面输入了8个数字,但是输出的count只有7个,当只有一个数字时,输入“No dat  processed.”,

知道的进来解释下,谢谢

编译器vs2010
[解决办法]
#include <iostream>
#include <fstream>
#include <cstdlib>

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);
if(!inFile.is_open())
{
cout<<"could not open the file "<<filename<<endl;
cout<<"Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;


while(inFile>>value)
{
++count;
sum += value;
}
  
if(inFile.eof())
{
cout<<"End of the file.\n";
}
else if(inFile.fail())
{
cout<<"Input terminated by data mismatch.\n";
}
  
if(count == 0)
{
cout<<"No data processed.\n";
}
else
{
cout<<"Items read:"<<count<<endl;
cout<<"Sum:"<<sum<<endl;
cout<<"Average:"<<sum/count<<endl;
}
return 0;
}

[解决办法]
读完最后一个数字后,它就不good了。
你应该是do while 逻辑。

热点排行