Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m working on a Project that requires the program to open a text file named in

ID: 3560311 • Letter: I

Question

I'm working on a Project that requires the program to open a text file named input.txt and read a list of numbers into an array. From there, the program should determine the number of items read from the file, and compute the sum, minimum, maximum, mean, and standard deviation of the data.

The list of numbers in the input.txt file will look something like this

For now, What I really need help with is the code for reading the list of numbers line by line into an array. Once I have that code I'll post another question regarding computing all the statistical items mentioned above and how to output a summary of the results in a text file named "output.txt"

If you have any questions let me know! Thanks!

Explanation / Answer


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

int main()
{
   char filename[25]="input.txt";
   int n = 0;
   FILE *ptr_file;
   ptr_file =fopen(filename, "r");
   if (!ptr_file)
       {
           printf("Error the file cannot be opened");
           exit(-1);
       }
   else
   {
       float i;
       fscanf (ptr_file, "%f", &i);
       n++;
       while (!feof (ptr_file))
   {
       //printf ("%f ", i);
           n++;
           fscanf (ptr_file, "%f", &i);
          
   }
   }
  
   fclose(ptr_file);
  
  
float *numArray = (float*)malloc(n*sizeof(float));

   ptr_file =fopen(filename, "r");
   float i;
   int x=0;
   fscanf (ptr_file, "%f", &i);
   while (!feof (ptr_file))
{
   //printf ("%f ", i);
       numArray[x++] = i;
       fscanf (ptr_file, "%f", &i);  
}
int j;
for( j=0; j<n; j++)
   printf("%.5f ", numArray[j] );
  
   return 0;
}