【问题标题】:File Handling - Value is being added two times instead of one [duplicate]文件处理 - 值被添加两次而不是一次 [重复]
【发布时间】:2021-05-04 15:45:04
【问题描述】:

当我运行我的代码时,它会将 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;
}

【问题讨论】:

标签: c++


【解决方案1】:

这种代码风格非常普遍,但也非常错误

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

请改成这样

while (file >> num1 >> num2) {

您的代码的问题是对eof 工作原理的误解。 Eof 测试您是否位于文件末尾,对吗?没有错。实际上,eof 测试您上次读取是否因为您位于文件末尾而失败。一个微妙的不同,这种不同解释了为什么你的循环似乎读取了最后一个项目两次。

如果您确实使用了eof,您应该在阅读后使用它来测试最后阅读是否失败。不是在读取之前预测下一次读取是否会失败。

【讨论】:

  • 一般规则: 1.读取数据。 2. 确保您读取数据。 3. 确保读取的数据在有效范围内。 4. 如果到目前为止一切都很好,请使用数据。如果您尝试乱序读取,例如在读取之前测试有效性,迟早会失败。
猜你喜欢
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 2020-01-20
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
相关资源
最近更新 更多