Thread: calculate the average value from a text file

  1. #1
    Registered User
    Join Date
    Jul 2020
    Posts
    4

    Unhappy calculate the average value from a text file

    Hello, I try to write a code to calculate the average value from a text file but the dumb thing is I has to count the no. of data manually to initialize the array. (here is 1000).

    Here is the code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(){
        
        
        FILE *p; 
        p = fopen("myfile.txt", "r");
    
    
        
        int Array[1000];
        int i;
        double sum=0.0;
        
        
    
    
       for (i = 0; i < 1000; i++)
    
    
    {
            fscanf(p, "%d", &Array[i] );
            
            printf("Number is: %d\t %d\n\n", Array[i],i);
            
            sum = sum + Array[i];
    }
            printf("The average weight is %lf",sum/1000);
    
    
            fclose(p);
    
    
            return 0;
    }
    It works but i just want it to count the no. of data automatically. So i search something that capable to count the no. :

    Code:
    #include<stdio.h>
    
    
    int main(void)
    {
        FILE *p;
        char ch;
        int w=0;
       
        p=fopen("myfile.txt","r");
        if(p==NULL)
         {
             printf("file not found");
          }
        else
          {
              ch=fgetc(p);
              while(ch!=EOF)
    
    
    {
                     
                      printf("%c",ch);
                            if(ch==' '||ch=='\n')
                              {
                                   w++;
                              }
                                   ch=fgetc(p);
    }
                                   printf("\nWords in a file are=%d",w);
         }
                                  fclose(p);
                                  getch();
    
    
    return 0;
    }
    How do I combine the two and make use of the 'w' in the first program? I've tried but fail. Hope someone can guide me.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You could do something like
    Code:
    int count = 0, value, sum = 0;
    while ( fscanf(p, "%d", &value ) == 1 ) {
      sum += value;
      count++;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jul 2020
    Posts
    4

    Thank you so much!

    Quote Originally Posted by Salem View Post
    You could do something like
    Code:
    int count = 0, value, sum = 0;
    while ( fscanf(p, "%d", &value ) == 1 ) {
      sum += value;
      count++;
    }
    Thank you so much! It works well !

    #include <stdio.h>




    Code:
    int main(){
    
    
    FILE *fpr; 
        fpr = fopen("elephant_seal.txt", "r");
    
    
    
    
    int count = 0, value;
    
    
    double sum = 0.0;
    
    
    while ( fscanf(fpr, "%d", &value ) == 1 ) {
      sum += value;
      count++;
    }
    
    
    printf("The average weight is %lf",sum/count);
    
    
            fclose(fpr);
    
    
            return 0;
    
    
    }

  4. #4
    Registered User
    Join Date
    Jul 2020
    Posts
    4
    Thank you! it works well. I am obsessed in assigning those value into array but turn out it is not necessary.



  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    You could keep 'sum' as integer (with more precision then individual values) and just convert to 'long double' (which have the same precision, in bits, as 'long long') when you calculate the mean:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
      // using 'long long' for 'sum', which have 2 times the precision of an 'int', in bits.
      long long sum;
      unsigned int count;
      int value;
      FILE *f;
    
      if ( !( f = fopen( "elephant_seal.txt", "r" ) ) )
      {
        fputs( "ERROR opening file.\n", stderr );
        return EXIT_FAILURE;
      }
    
      count = 0;
      sum = 0LL;
    
      while ( fscanf( f, "%d", &value ) == 1 )
      {
        sum += value;
        count++;
      }
    
      fclose( f );
    
      if ( ! count )
      {
        fputs( "ERROR: Couldn't read any values!\n", stderr );
    
        return EXIT_FAILURE;
      }
    
      // Need to be 'long double' since 'double' has only 53 bits of precision!
      printf( "The average weight is %.3Lf", ( long double )sum / count );
    
      return EXIT_SUCCESS;
    }
    Last edited by flp1969; 07-22-2020 at 08:41 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trying to calculate a running average
    By knik653 in forum C Programming
    Replies: 18
    Last Post: 11-11-2018, 11:57 AM
  2. How to calculate the average of scores?
    By david.jones in forum C Programming
    Replies: 4
    Last Post: 05-02-2011, 06:33 AM
  3. Replies: 26
    Last Post: 08-19-2009, 07:59 AM
  4. calculate average
    By archriku in forum C Programming
    Replies: 23
    Last Post: 04-10-2009, 04:27 AM
  5. calculate average from a file
    By mrsirpoopsalot in forum C++ Programming
    Replies: 11
    Last Post: 01-20-2009, 02:25 PM

Tags for this Thread