关于C代码的Fscanf

时间:2015-11-05 20:26:45

标签: c

我必须编写C代码来读取.txt文件的一些int数(在我的情况下为1 2 3 4 5 6 7 8 9)并在int数组上组织它们。然后你必须声明三个函数,它们返回数字的最大数量,最小值和平均值。在这种情况下,结果必须是915。 为什么这不是我想做的事情?感谢一些帮助,对不起我的英语。

#include <stdio.h>
#include <stdlib.h>

int Maximum(int array[]){
    int maximo=0, i;
    for(i=0;array[i]!=0;i++){
        if(array[i]>maximo){
            maximo=array[i];
        }
    }
    return(maximo);
}

int Minimum(int array[]){
    int minimo=0, i;
    for(i=0;array[i]!=0;i++){
        if(array[i]>minimo){
            minimo=array[i];
        }
    }
    return(minimo);
}

int Average(int array[]){
   float average;
   int i, suma=0;
   for(i=0;array[i]!=0;i++){
       suma+=array[i];
   }
   average=suma/i;
   return(average);
}



int main(void) { 
    int i, max, min;
    float med;
    int number[100];
    FILE *idf; 
    idf=fopen("Exercise_1.txt", "rt");
    if (idf==NULL)
        printf("ERROR openning file...");
    else {
        for(i=0;number[i]!='\0';i++){
            if(number[i]!=' '){
                fscanf(idf,"%d",&number[i]);                
            }
        }        
    }
    int fclose (FILE* idf);

    max=Maximum(number);
    min=Minimum(number);
    med=Average(number);

    printf("Max number: %d", max);
    printf("\nMin number: %d", min);
    printf("\nAverage: %f", med);

    return 0;
}

这样做之后我得到了非常高的数字。

1 个答案:

答案 0 :(得分:0)

这部分发布的代码:

if (idf==NULL)
    printf("ERROR openning file...");
else {
    for(i=0;number[i]!='\0';i++){
        if(number[i]!=' '){
            fscanf(idf,"%d",&number[i]);                
        }
    }        
}

包含一些问题

1) it will exit the loop early 
   if some un-initialized value in the `number[100]` array 
      happens to be all 0x00
2) it does not pay attention to the returned value from `fscanf()` 
   so does not know when EOF is reached or an I/O error occurs.
3) it does not set a final entry in the `numbers[100]` array 
   to the termination flag `0` 
   BTW: poor method for indicating last entry in array
        Suggest using the variable 'i' and passing 'i' to each
        of the sub functions
4) it keeps executing when the `fopen()` function 
   returned a failure condition

建议像这样写:

// always place literal on left so compiler can catch `=` 
//   when should be `==` errors
if( NULL == idf )
{ // then fopen failed
    perror( "fopen for Exercise_1.txt for read failed" );
    exit( EXIT_FAILURE );
}

// implied else, fopen successful

// pre-init array to all 0 - this is a problem if input contains a 0
memset( number, 0x00, sizeof( number ) );

// input numbers into array until EOF or I/O error
for( i=0; 1==fscanf( idf, "%d", &number[i] ); i++ ) {;}