c++ - 文件处理 - 值被添加两次而不是一次
问题描述
当我运行我的代码时,它会将 81 的值添加两次。为什么 ???
编写一个程序来读取文件 Squares.txt 的内容,并在名为 Analysis.txt 的文件中显示所有数字的总和、所有数字的平均值、最大数字和最小数字。Squares.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
了,你应该在阅读后使用它来测试最后一次阅读是否失败。不是在阅读之前预测下一次阅读是否会失败。
推荐阅读
- flutter - 为在颤动中单击的每个按钮更改 appBar
- r - 如何在 R 中创建一个函数以将变量重新编码为新的二进制列?(带有 ifelse 语句)
- julia - 在 Julia 中正确指示路径
- node.js - nohup究竟是如何工作的,为什么后台处理节点会导致端口冲突
- flutter - 如何在 Flutter 中为底部工作表及其内容设置动画
- flutter - 从函数调用返回 Flutter 值
- ios - Cocoapods 为 iOS 和 watchOS 安装 SwiftAA 而不是 macOS Catalyst
- python - 如何使用 Django rest 框架将照片上传到我的计算机中的文件
- flutter - 在 Fluttter 中,如何为 Card 中的子元素动态分配 hight?
- flutter - 将回调函数传递给子状态小部件(现代 Flutter)