#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
int main()
{
char fileName[SIZE];
ifstream inFile;
cout << "Please enter the file name:";
cin.getline(fileName,SIZE);
inFile.open(fileName);
if(!inFile.is_open())
{
cout << "Sorry! This file can't open ."
<< "Program terminating.";
exit(EXIT_FAILURE);
}
double value;
double sum=0;
int count=0;
inFile >> value;
while(inFile.good())
{
++count;
sum += value;
inFile >> value;
}
if(inFile.eof())
cout << "It's the end of the file.\n";
else if(inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated by unknown reason.\n";
程序代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
int main()
{
char fileName[SIZE];
ifstream inFile;
cout << "Please enter the file name:";
cin.getline(fileName,SIZE);
inFile.open(fileName);
if(!inFile.is_open())
{
cout << "Sorry! This file can't open ."
<< "Program terminating.";
exit(EXIT_FAILURE);
}
double value;
double sum=0;
int count=0;
//inFile>>value;这个要去掉,因为运行了这个后,文件指针已经指向了后面,你试着只分析3个数据就会明白的
while(inFile.good())
{ inFile >> value;
++count;
sum += value;
}
if(inFile.eof())
cout << "It's the end of the file.\n";
else if(inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated by unknown reason.\n";