Thread: Homework: Read and Print to file - Am I oversimplifying?

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    70

    Homework: Read and Print to file - Am I oversimplifying?

    Ok, I think I got the main idea of the I/O chapter. Though I think I might be oversimplifying the program because I am getting an interesting error.

    Goal here is to read numbers from a file and print the numbers with totals for two of the columns and a calculated average for of the totals.

    NOTE: The tables for the info from file look a lot better on my end. [QUOTE] seems to mess it up a bit from copying and pasting.

    Info from problem:
    Car No. Miles Driven Gallons Used
    ----------------------------------------------------
    54 250 19
    62 525 38
    71 123 6
    85 1,322 86
    97 235 14
    carinfo.txt file:
    54 250 19
    62 525 38
    71 123 6
    85 1322 86
    97 235 14
    program:

    Code:
    updated code
    Last edited by Cameron Taylor; 07-15-2013 at 08:24 PM.

  2. #2
    Registered User
    Join Date
    Jun 2013
    Posts
    70
    This is my output from GCC

    Floating point exception (core dumped)
    I have used -w and -Wall and their are no errors the compiler can find.

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Two errors.

    1. You haven't initialized total_gal and total_mil:
    Code:
    int total_gal = 0, total_mil = 0;
    2. You aren't controlling the loop correctly. The end-of-file indicator
    is not set until the fscanf fails, so you should be checking there:
    Code:
     while(fscanf(infile,"%d %d %d",&car_num, &miles, &gallons) == 3) 
     {

  4. #4
    Registered User
    Join Date
    Jun 2013
    Posts
    70
    Code:
    #include <stdio.h>
      
    int main()
    {
        FILE *infile,*outfile;
        double car_num, miles, gallons;
        double total_gal = 0, total_mil = 0, i;
        double mph = 0;
          
        infile=fopen("/home/commiedic/Documents/Project15/carinfo.txt","r");
        outfile=fopen("/home/commiedic/Documents/Project15/gross.txt","w");
      
        while(!feof(infile))
        {
            fscanf(infile,"%f %f %f",&car_num, &miles, &gallons);
    
                total_mil += miles;
                total_gal += gallons;
                mph = total_mil / total_gal;
    
            fprintf(outfile,"\nCar No.\tMiles Driven\tGallons Use\tTotal Miles\tTotal Gallons\tAverage MPG");
            fprintf(outfile,"--------------------------------------------------------------------------------------------");
            fprintf(outfile,"%f\t%f\t%f\t%f\t%f\t%f",car_num,miles,gallons,total_mil,total_gal,mph);
        }
      
        fclose(infile);
        fclose(outfile);
          
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    If you want to preserve the number of spaces between things (like table data) when you copy-paste, put it int code tags (not quote tags). That will use a fixed-width font, and not compress spaces.

    Are you sure it's GCC that is producing that error (i.e. does that happen when you compile your program)? Or is it your program that produces that when you run it? Either way, that is a run-time error, not necessarily something the compiler can catch. See here for some possible causes of an FPE: Help - AIX 7.1 Information Center. It's more likely your program has the bug (not GCC) and it's one of your calculations is causing a problem. What, for example, are the initial values of total_gal and total_mil, before you start adding to them?

    Also, read this: FAQ > Why it's bad to use feof() to control a loop - Cprogramming.com. Change your loop to use the return value of fscanf. It should return the number of items scanned (3 in your case).

    it may be worth noting, mph stands for miles per hour. You seem to be calculating miles per gallon, or mpg. Might want to fix that variable name.

    Lastly, the % operator is modulo (remainder). You probably want division (/). Note, since both operands (total_mil and total_gal) are integers, you will get integer division, i.e. it will throw away the fractional part. Cast one operand to double to get floating point division:
    Code:
    mpg = ((double) total_mil) / total_gal;
    EDIT: And check infile and outfile for NULL (fopen failed) before proceeding. If either fopen fails, print an error and exit with an error code.

  6. #6
    Registered User
    Join Date
    Jun 2013
    Posts
    70
    Ok, I figured it out. It was because in the input file I separated the numbers with tab instead of just a space. Been tweaking it a bit more and this is what i got so far.

    Code:
    #include <stdio.h>
      
    int main()
    {
        FILE *infile,*outfile;
        int car_num, miles, gallons;
        int total_gal, total_mil;
        double mpg;
          
        infile=fopen("/home/commiedic/Documents/Project15/carinfo.txt","r");
        outfile=fopen("/home/commiedic/Documents/Project15/gross.txt","w");
    
        fprintf(outfile,"\nCar No.\tMiles Driven\tGallons Use\tTotal Miles\tTotal Gallons\tAverage MPG\n");
        fprintf(outfile,"--------------------------------------------------------------------------------------------\n");
    
        while(!feof(infile))
        {
            fscanf(infile,"%d %d %d",&car_num, &miles, &gallons);
    
            total_mil += miles;
            total_gal += gallons;
            mpg = total_mil / total_gal;
    
        fprintf(outfile,"%d\t%d\t%d\t%d\t%d\t%f",car_num,miles,gallons,total_mil,total_gal,mpg);
        }
    
        fclose(infile);
        fclose(outfile);
    
        return 0;
    }
    my output:

    Code:
    Car No.    Miles Driven    Gallons Use    Total Miles    Total Gallons    Average MPG
    --------------------------------------------------------------------------------------------
    
    54    250    19    250    19    13.000000
    62    525    38    775    57    13.000000
    71    123    6    898    63    14.000000
    85    1322    86    2220    149    14.000000
    97    235    14    2455    163    15.000000
    97    235    14    2690    177    15.000000
    the input file:
    Code:
    54 250 19
    62 525 38
    71 123 6
    85 1322 86
    97 235 14
    Last edited by Cameron Taylor; 07-15-2013 at 08:49 PM.

  7. #7
    Registered User
    Join Date
    Jun 2013
    Posts
    70
    Thanks for this line!

    Code:
    mpg = ((double) total_mil) / total_gal;
    New output all working.

    lol, it is perfectly aligned in my txt document. Guess I can't win with pasting it. Even when using [CODE] =P

    Code:
    Car No.        Miles Driven    Gallons Use    Total Miles    Total Gallons    Average MPG
    -------------------------------------------------------------------------------------------
    
    54        250        19        250        19        13.16
    62        525        38        775        57        13.60
    71        123        6        898        63        14.25
    85        1322        86        2220        149        14.90
    97        235        14        2455        163        15.06
    97        235        14        2690        177        15.20

  8. #8
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you can use spaces instead of \t
    Code:
    #include <stdio.h>
    int main(void)
    {
        printf("%7s%15s%15s%15s%15s%10s\n",
            "Car No.","Miles Driven", "Gallons Use", "Total Miles","Total Gallons","Average"); 
    
        printf("%7d%15d%15d%15d%15d%10.2f\n",
            54,    250 ,   19 ,   250 ,   19  ,  13.000000); 
        printf("%7d%15d%15d%15d%15d%10.2f\n",
            71,    123  ,  6 ,   898 ,   63 ,   14.000000); 
        printf("%7d%15d%15d%15d%15d%10.2f\n",
            85 ,   1322   , 86   , 2220   , 149   , 14.000000); 
    
        return 0;
    }
    Result
    Code:
    Car No.   Miles Driven    Gallons Use    Total Miles  Total Gallons   Average
         54            250             19            250             19     13.00
         71            123              6            898             63     14.00
         85           1322             86           2220            149     14.00
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    5 lines of input, and 6 lines of output.

    Output
    > 97 235 14 2455 163 15.000000
    > 97 235 14 2690 177 15.000000

    Input
    > 97 235 14

    > while(!feof(infile))
    Now go and read post #5 again.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-26-2013, 06:21 AM
  2. Replies: 3
    Last Post: 03-13-2013, 07:10 PM
  3. Help with Binary Print Homework
    By jewleeuhn in forum C Programming
    Replies: 1
    Last Post: 11-21-2011, 03:30 AM
  4. Read struct-like file/print to stdout (again)
    By inakappeh in forum C Programming
    Replies: 3
    Last Post: 09-18-2001, 04:33 AM