Thread: Reading Floats from a File

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    27

    Reading Floats from a File

    I have a C assignment that reads a provided file and finds specific values from the data set, which is a list of decimal values in a txt file. The program runs but the output is no where close to what it should be. What am I doing wrong? You may disregard the variables std_dev and range which are a separate step of the assignment.
    Attached Files Attached Files

  2. #2
    Banned
    Join Date
    Aug 2017
    Posts
    861
    how you are filling your array for one,
    Code:
            double data[300];
            int Fsize = 0;
            while(!feof(fpin))
            { 
                 // fills an array type double
                 fscanf(fpin, "%lf", &data[Fsize]);
                 Fsize++; // get actual count of size used as well
            }
    if you didn't you're going to want 'a ::: check your min start value as well.
    Last edited by userxbw; 11-04-2017 at 03:46 PM.

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    how you are filling your array for one,
    Code:
            double data[300];
            int Fsize = 0;
            while(!feof(fpin))
            { 
                 // fills an array type double
                 fscanf(fpin, "%lf", &data[Fsize]);
                 Fsize++; // get actual count of size used as well
            }
    if you didn't you're going to want 'a ::: check your min start value as well.
    You're going to have to really, really, really, really dumb that down for me to understand. I have no background in any coding.

  4. #4
    Banned
    Join Date
    Aug 2017
    Posts
    861
    My curiosity is up now. How did you get to opening files and reading them, before you had been given exposure on arrays?
    in other words,
    How to loop arrays to get values in and out of them?

    COMMENTS INSIDE OF CODE


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    // NOT NEEDED 
    // YOU'RE NOT USING ANY MATH FUNCTIONS
    //JUST DOING BASIC MATH WITHOUT FUNCTIONS TO 
    //DO THEM FOR YOU
    
    //#include <math.h>
    
    
    /*** MY TEST FILE IS THIS 
    3.900000
    3.700000
    4.200000
    1.000000
    6.100000
    9.700000
    * 
    *  total 28.6 / 6 = adv 4.7666 rounded 4.77
    * 
    * ****/
    
    #define MAX_SZ 300
    int main()
    {
        int data[MAX_SZ];   // ARRAY TYPE INT you're using double
        int Fsize = 0;
        int  i=0;    //array of data
        double data_in, min=0.0, max=0.0;     //max and min of data set
        double sum = 0.0, avg;     //average, standard deviation, range of data set
        
          
        
    // YOUR CODE
    // NO ARRAY BEING FILLED
    // the only thing inside of your array is crap memory/data values
    // given to it by the computer it is running on. 
    
        FILE *fpin;
        fpin = fopen("data.txt","r");
    
        for(i=0;i<199;i++)
        {
            fscanf(fpin, "%lf", &data_in); // NO ARRAY BEING FILLED
           if (data[i]>max) // NO ARRAY VALUES TO READ
           {
               max = data[i]; // NO ARRAY VALUES TO ASSIGN
           }
           if (data[i]<min) // NO ARRAY VALUES TO READ
           {
               min = data[i]; // NO ARRAY VALUES TO ASSIGN
           }
        }
            for(i=0;i<199;i++)
            {
               fscanf(fpin, "%lf", &data_in);
               sum += data[i]; // NO ARRAY VALUES TO ADD UP
               avg = sum / 200.0; // NO REAL RESULTS 
            }
        printf("\n\n scotdani code\n\n");
        printf("The sum value of this data set is %.02lf.\n\n", sum);
        printf("The minimum value of this data set is %lf.\n", min);
        printf("The maximum value of this data set is %lf.\n", max);
        printf("The average value of this data set is %lf.\n", avg);
        printf("----------------------------------------------------\n");
        printf("----------------------------------------------------\n");
        printf("\n");
    
    
        
        
    // OPERATION ONE
    
    // DOES COMPUTATIONS AND FILLS ARRAY AT SAME TIME
    
    // PROPER DATA TYPE ARRAY OF DOUBLE
        double data1[MAX_SZ] = { 0.0 };
     
        // reset everything
    
        fseek(fpin, 0, SEEK_SET);
        
    
    // SET MIN TO GREATER THAN 0.0 THAT IS THE LOWEST 
    //IT WILL PRODUCE FALSE READING IF DATA IN FILE IS GREATER THAN 0.0
    //NOTHING IN FILE CAN GET LOWER THAN 0.0 UNLESS IT IS -NEG THEN
    //THAT IS NEGATIVE ISN'T IT. -1.0, 0.0, 0.1
    
        sum = 0.0 , min=9999999990.0, max=0.0, avg = 0.0, data_in = 0.0; // reset values
        Fsize = 0;
    
        
        
        // makes array obsolete because everything 
        // is being done while reading
        //the data and storing it into the array.
        // this only makes the
        // array useful if user needs it
        // for later on. 
    
        while(!feof(fpin)) // seeks for end of file when found loops stops. 
        {
            fscanf(fpin, "%lf", &data1[Fsize]);
            
            if (data1[Fsize]>max)
            {
                max = data1[Fsize];
            }
            if (data1[Fsize]<min)
            {
                min = data1[Fsize];
            }
            sum += data1[Fsize];
                
                Fsize++; // moves the array elements by value inside of it
        }
        //avg = sum / 200.0;
        avg = sum / 6.0;
        
      
           
        printf("The sum value of this data1 set is %.02lf.\n\n", sum);
        printf("The minimum value of this data1 set is %.02lf.\n", min);
        printf("The maximum value of this data1 set is %.02lf.\n", max);
        printf("The average value of this data1 set is %.02lf.\n", avg);    
        printf("----------------------------------------------------\n");
        printf("\n");
        
    
    // OPERATION TWO
    
    // DOES COMPUTATIONS WITHOUT USE OF AN ARRAY
    
        //reset everything
         fseek(fpin, 0, SEEK_SET);
       
       
        sum = 0.0 , min=9999999990.0, max=0.0, avg = 0.0, data_in = 0.0;
        Fsize = 0;
        // here the same thing 
        // is taking place
        // without storing
        // data into a contaner typed 
        // as an array
        for(i=0;i<6;i++)
        {
            fscanf(fpin, "%lf", &data_in);
            
            if (data_in>max)
            {
                max = data_in;
            }
            if (data_in<min)
            {
                min = data_in;
            }
            sum += data_in;     
        }
        //avg = sum / 200.0;
        avg = sum / 6.0;
        
        printf("The sum value of this data1 set is %.02lf.\n\n", sum);
        printf("The minimum value of this data1 set is %.02lf.\n", min);
        printf("The maximum value of this data1 set is %.02lf.\n", max);
        printf("The average value of this data1 set is %.02lf.\n", avg);
        printf("----------------------------------------------------\n");
           printf("\n");
     
    
    
    
    // OPERATION THREE
    
    // FILLS ARRAY THEN DOES THE COMPUTATIONS ON DATA WITHIN SAME ARRAY
    
        // reset everything
        fseek(fpin, 0, SEEK_SET);
      
        for ( int i = 0; i<MAX_SZ; i++) data1[i] = 0.0;
        sum = 0.0 , min=9999999990.0, max=0.0, avg = 0.0, data_in = 0.0; 
        Fsize = 0;
        
        while(!feof(fpin))
        { 
            // fills an array type double
            fscanf(fpin, "%lf", &data1[Fsize]);
            Fsize++; // get actual count of size used as well
        }
        for ( i = 0; i < Fsize; i++)
        {
            if (data1[i]>max)
            {
                max = data1[i];
            }
            if (data1[i]<min)
            { 
                min = data1[i];
            }
            sum += data1[i];
        }
        //avg = sum / 200.0;
        avg = sum / 6.0;
        
        printf("The sum value of this data1 set is %.02lf.\n\n", sum);
        printf("The minimum value of this data1 set is %.02lf.\n", min);
        printf("The maximum value of this data1 set is %.02lf.\n", max);
        printf("The average value of this data1 set is %.02lf.\n", avg);
        printf("\n");
        fclose(fpin); // Close File after Reading
        
        return 0;
    }
    Results
    Code:
    $ ./reading_floats_from_a_file
    
    
     scotdani code
    
    The sum value of this data set is -13910352430.00.
    
    The minimum value of this data set is -1565315752.000000.
    The maximum value of this data set is 2027877040.000000.
    The average value of this data set is -69551762.150000.
    
    ----------------------------------------------------
    ----------------------------------------------------
    
    The sum value of this data1 set is 28.60.
    
    The minimum value of this data1 set is 1.00.
    The maximum value of this data1 set is 9.70.
    The average value of this data1 set is 4.77.
    ----------------------------------------------------
    
    The sum value of this data1 set is 28.60.
    
    The minimum value of this data1 set is 1.00.
    The maximum value of this data1 set is 9.70.
    The average value of this data1 set is 4.77.
    ----------------------------------------------------
    
    The sum value of this data1 set is 28.60.
    
    The minimum value of this data1 set is 1.00.
    The maximum value of this data1 set is 9.70.
    The average value of this data1 set is 4.77.
    
    userx@slackwhere:~/bin
    Last edited by userxbw; 11-04-2017 at 09:14 PM.

  5. #5
    Banned
    Join Date
    Aug 2017
    Posts
    861
    just a little on array's
    Code:
    double array[amount of elements wanted]; // takes in double values
    float array[amount of elements wanted]; // takes in float values
    int array[amount of elements wanted]; // takes in int values
    
    //to add values inside of each element one at a time.
    int count; // the array's are zero based, 0 thru .... so the elements are integers.
    
    
    // putting values inside of an array, amount is or can be an unknown
    for (count = 0; count < amount_of_data_being_read_in; count++)
    {
          array[count] = value_being_put_inside_of_it;
    }
    
    
    // count already holds the amount of elements used.
    
    
    //to get values out of array one at a time; 
    //Because size is now a known. We use count again. 
    // count prevents the over shooting of the array. 
    
    for (int  i = 0; i < count; i++)
    {
        printf("Array element Number is %d \nvalue inside of array[ %d ]\n", i , array[ i ]);
    }

    Knowing the amount of data being read in needs to be found out ahead of time so the programmer can have a really good idea on how big to make the array. If not known then all one can do is guess. So making an array bigger then one might expect to use is not a bad idea for them just in case situations.

    this is why the programmer needs at least an idea of how big will the data will be so he or she can code for that.

    dynamic growth is a way to get around that
    Last edited by userxbw; 11-04-2017 at 10:12 PM.

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Using feof() to control loops is a mistake most of the time.

    Pick one of these, or read them all if you want:
    FAQ > Why it's bad to use feof() to control a loop - Cprogramming.com
    Things to Avoid in C/C++ -- feof(), Part 3 - GIDNetwork
    c - Why is “while ( !feof (file) )” always wrong? - Stack Overflow

    To make feof() work like it should, you need to try to read something before you test. So, this could be right:
    Code:
    int rv, i, array[100];
    double data_in;
    FILE *f;
    
    f = fopen("data.txt", "r");
    i = 0;
    rv = fscanf(f, "%lf", &data_in);
    while (!feof(f) && rv == 1 && i < 100) {
       array[i++] = data_in;
       rv = fscanf(f, "%lf", &data_in);
    }
    However, at this point, the !feof(f) test is just something extra; the return value of fscanf() tells you everything that feof() can and more. So the code can be even more simple...
    Code:
    while ((rv = fscanf(f, "%lf", &data_in)) == 1 && i < 100) {
       array[i++] = data_in;
    }
    I also like that data_in is used in the original code, but that is nothing but a preference. Passing in &array[i] to fscanf() is completely correct.

  7. #7
    Banned
    Join Date
    Aug 2017
    Posts
    861
    here fscanf is not even checking for eof

    C library function fscanf()


    this is where I got my information
    How to use EOF to run through a text file in C? - Stack Overflow


    Code:
    Using fread():
    char buffer[BUFFER_SIZE];
    while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                         // element of size
                                                         // BUFFER_SIZE
    {
       // process buffer
    }
    if (feof(stream))
    {
      // hit end of file
    }
    else
    {
      // some other error interrupted read
    }  
    Note that the form is the same for all of them: check the result of the read operation; if it failed,
     then check for EOF.  You'll see a lot of examples like:
      while(!feof(stream))
    {
      fscanf(stream, "%s", buffer);
      ...
    } 
      Note that the form is the same for all of them:
    that is as far as I read.
    Last edited by userxbw; 11-05-2017 at 07:06 AM.

  8. #8
    Registered User
    Join Date
    Nov 2017
    Posts
    27
    I'll take some time to digest all of this. We had one lecture just last week lumping arrays and file I/O together. It's been a very bumpy learning experience to say the least.

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by userxbw View Post
    this is where I got my information
    How to use EOF to run through a text file in C? - Stack Overflow


    Code:
    Using fread():
    char buffer[BUFFER_SIZE];
    while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                         // element of size
                                                         // BUFFER_SIZE
    {
       // process buffer
    }
    if (feof(stream))
    {
      // hit end of file
    }
    else
    {
      // some other error interrupted read
    }  
    Note that the form is the same for all of them: check the result of the read operation; if it failed,
     then check for EOF.  You'll see a lot of examples like:
      while(!feof(stream))
    {
      fscanf(stream, "%s", buffer);
      ...
    } 
      Note that the form is the same for all of them:
    that is as far as I read.
    Perhaps you should have kept reading? Your own source goes on to say this.
    This form doesn't work the way people think it does, because feof() won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.

  10. #10
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by scotdani View Post
    I'll take some time to digest all of this. We had one lecture just last week lumping arrays and file I/O together. It's been a very bumpy learning experience to say the least.
    he should have covered array's first then gave out homework for the students to get use to using them first, then moved on to files and how to apply arrays to them so one hopefully could gain a better understanding on how array's can be used in conjunction with files. Then the teacher would have given the student a better chance to make that connection between the two of them greater.

  11. #11
    Registered User
    Join Date
    Nov 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    he should have covered array's first then gave out homework for the students to get use to using them first, then moved on to files and how to apply arrays to them so one hopefully could gain a better understanding on how array's can be used in conjunction with files. Then the teacher would have given the student a better chance to make that connection between the two of them greater.
    I agree the structure can be greatly improved for this course. The first coding lecture covered how to read and calculate binary and hex and convert between all of them. There are plenty of things that are backwards in my opinion, particularly that my declared major has little to nothing to do with writing code.

  12. #12
    Registered User
    Join Date
    Nov 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    My curiosity is up now. How did you get to opening files and reading them, before you had been given exposure on arrays?
    in other words,
    How to loop arrays to get values in and out of them?

    COMMENTS INSIDE OF CODE


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    // NOT NEEDED 
    // YOU'RE NOT USING ANY MATH FUNCTIONS
    //JUST DOING BASIC MATH WITHOUT FUNCTIONS TO 
    .
    .
    .
    .
    userx@slackwhere:~/bin

    I loaded your example here into my compiler, CodeBlocks 16.01, and it doesn't like the last for loop you wrote, line 181. Reading through it line by line I just got confused because I don't have a good foundation on loops. While and Do While I am ok with, but For loops are completely foreign to me. Honestly I learn better by watching and doing stuff, definitely not by reading.

  13. #13
    Registered User
    Join Date
    Jun 2017
    Posts
    88
    1. printf, scanf
    2. if, else, while
    3. for, switch, do
    4. functions, scope, random, recursion
    5. arrays, search, sort
    6. pointers, sizeof
    7. character functions, string functions
    8. advanced printf, advanced scanf
    9. structs, bitwise
    10. file processing
    11. linked lists, stacks, queues, trees
    12. preprocessor directives
    13. redirecting I/O, command line arguments, dynamic memory

    is the order the book I learn from arranges subjects. I think it is a good order, except I would move dynamic memory in with arrays. I had to do that anyway since I can't use variable length arrays in my IDE. Binary calculations should be a part of bitwise, and base conversion (hex, oct, binary, dec) is an appendix subject.
    Last edited by jack jordan; 11-05-2017 at 01:08 PM.

  14. #14
    Registered User
    Join Date
    Jun 2017
    Posts
    88
    For loops are completely foreign to me.
    for loops are really just a one liner for a common loop structure.
    Code:
    for (int i = 0; i < 10; ++i) {
        // do something
    }
    is the same thing as:
    Code:
    int i = 0;
    while (i < 10) {
        // do something
        ++i;
    }
    The only reasons to use for loops is either if you want to be lazy/efficient or you think for loops look nicer. I use them for these reasons, but while is easier to debug.
    Last edited by jack jordan; 11-05-2017 at 03:23 PM.

  15. #15
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by whiteflags View Post
    Perhaps you should have kept reading? Your own source goes on to say this.
    yeah I know I am eating crow for that already thanks. !! you want some?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can't read floats into 2D array from file
    By std10093 in forum C++ Programming
    Replies: 3
    Last Post: 04-12-2014, 09:36 AM
  2. Newbie at C, about reading floats into an array
    By someoney3000 in forum C Programming
    Replies: 9
    Last Post: 10-14-2009, 12:40 PM
  3. Reading errors in floats
    By Improvolone in forum C++ Programming
    Replies: 8
    Last Post: 03-21-2006, 03:20 PM
  4. reading int's and floats...
    By flightsimdude in forum C Programming
    Replies: 8
    Last Post: 09-20-2003, 01:17 PM

Tags for this Thread