文件处理-值被添加了两次而不是一次



当我运行代码时,它将81的值相加两次。为什么? ?

编写程序读取文件Squares.txt的内容并显示所有数的和,所有数的平均值,最大的一个名为Analysis.txt的文件中最小的数字。

Number Square
3        9
5        25
1        1
7        49
9        81
#include <iostream>
using namespace std ;
#include <fstream>
int main() {
ifstream file ;
char arra[100];
int num1,num2,avg;
int sum=0 ;
int smallest = 9999 ;
int highest = -999 ;
int count= 0 ;
cout<<"Open file square.txt..."<<endl ;
file.open("/Users/kchumun/Documents/Xcode/Labsheet 8(3)/square2.txt") ;
if(!file){
cout<<"File cannot be opened !"<<endl ;
}else {
cout<<"File opened !"<<endl;
file.get(arra,100) ;
while(!file.eof()){
file>>num1;
file>>num2 ;
sum+=num2;
count++ ;
if(num2<smallest){
smallest = num2 ;
}
if (num2>highest) {
highest = num2 ;
}
}
}
file.close() ;
avg= sum / count ;
cout<<"Sum= "<<sum<<endl ;
cout<<"Average= "<<avg<<endl;
cout<<"Highest= "<<highest<<endl ;
cout<<"Smallest= "<<smallest<<endl;

ofstream File ;
cout<<"Open file Analysis "<<endl ;
if(!File){
cout<<"Error !" ;
}else{
File.open("/Users/kchumun/Documents/Xcode/Labsheet 8(3)/Analysis.txt");
File<<"Sum= "<<sum<<endl ;
File<<"Averagem= "<<avg<<endl;
File<<"Highest= "<<highest<<endl ;
File<<"Smallest= "<<smallest<<endl ;
}
File.close();
cout<<"Operation completed !";

return 0;
}

这种风格的代码非常常见,但也非常错误

while(!file.eof()){
file>>num1;
file>>num2;

请改成这样

while (file >> num1 >> num2) {

你的代码的问题是对eof如何工作的误解。Eof测试你是否在文件的末尾,对吗?不,错了。在现实中,eof测试如果你的最后一次读取失败,因为你在文件的末尾。这是一个微妙的不同,这个不同解释了为什么循环似乎读取最后一项两次。

如果你使用eof,你应该在之后使用读取最后一个读取失败。

相关内容

最新更新