VC ++ 6.0读取TXT数字问题,问题在注释中 30
#include<iostream>#include<fstream>constintSIZE=60;intmain(){usingnamespacestd;charfi...
#include<iostream>
#include<fstream>
const int SIZE=60;
int main()
{
using namespace std;
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()) // 用这个读取数字,最后一个就不读取了,例如文本里面有1 2 3一 共3个数字的话,他只读取1和2,我用VS2015测试就可以,把测试条件换成infile>>value相应都改了 也可以了,求解啊.
{
++count;
sum+=value;
inFile>>value;
}
if(inFile.eof())
cout<<"end of file reached.\n";
else if(inFile.fail())
cout<<"input terminated by data mismatch.\n";
else
cout<<"input terminated for unknown reason.\n";
if (count==0)
cout<<"no data processed";
else
{
cout<<"item read:"<<count<<endl;
cout<<"sum: "<<sum<<endl;
cout<<"average: "<<sum/count<<endl;
}
inFile.close();
return 0;
} 展开
#include<fstream>
const int SIZE=60;
int main()
{
using namespace std;
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()) // 用这个读取数字,最后一个就不读取了,例如文本里面有1 2 3一 共3个数字的话,他只读取1和2,我用VS2015测试就可以,把测试条件换成infile>>value相应都改了 也可以了,求解啊.
{
++count;
sum+=value;
inFile>>value;
}
if(inFile.eof())
cout<<"end of file reached.\n";
else if(inFile.fail())
cout<<"input terminated by data mismatch.\n";
else
cout<<"input terminated for unknown reason.\n";
if (count==0)
cout<<"no data processed";
else
{
cout<<"item read:"<<count<<endl;
cout<<"sum: "<<sum<<endl;
cout<<"average: "<<sum/count<<endl;
}
inFile.close();
return 0;
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询