Thread: Another "reading from a file" question

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    10

    Another "reading from a file" question

    I wrote my program. It compiles, but when I run it, it doesn't print out my data, just my headers. Well, it prints my first header once, and then my second headers four times. Any thoughts and help would be greatly appreciated.

    Code:
    #include<stdio.h>
    int main()
    {
       int carNum, carMiles, carGal;
       float galsMile;
       int totalMiles, totalAve, totalGal;
       FILE *in;
       totalGal = 0;
       totalMiles = 0;
    
       in = fopen("cardata.txt", "r");
       if (in == NULL)
        {
         printf("Could not open file. \n");
         exit(1);
        }
       
        printf("Car Number Miles Gallons Miles Per Gallon \n");
       while((fscanf(in,"%d %d %d", &carNum, &carMiles, &carGal)) != EOF)
        {
         galsMile = carMiles / carGal;
         fprintf(in, "%d %d %d %.2f \n", carNum, carMiles, carGal, galsMile);
         totalGal = totalGal + carGal;
         totalMiles = totalMiles + carMiles;
         totalAve = totalMiles / totalGal;
         printf("Total Gallons Total Miles Total Mile Per Gallon \n");
         fprintf(in, "%d %d %.2f \n", totalGal, totalMiles, totalAve);
        }
    
       fclose(in);
      return 0;
    }
    Dazed and Confuzed

  2. #2
    cereal killer dP munky's Avatar
    Join Date
    Nov 2002
    Posts
    655
    dont you need an else w/your if???

    ...or does it matter in this case
    guns dont kill people, abortion clinics kill people.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>dont you need an else w/your if???
    No, not needed.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User
    Join Date
    Nov 2002
    Posts
    10

    Thanks

    Hey Ya'll,
    I fixed my problems the night i posted this, but thanks for all of your comments any ways: ) The ones that you pointed out were the ones that I found with an additional cast problem, which a friend pointed out. So thanks alot.
    Sacha

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Question about linked lists.
    By cheeisme123 in forum C++ Programming
    Replies: 6
    Last Post: 02-25-2003, 01:36 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM