Thread: Open up file, read file until EOF, and report count and sum of all numbers?

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    6

    Open up file, read file until EOF, and report count and sum of all numbers?

    I'm having trouble with how to find the count and sum of all numbers. Please help?
    The file, called question1.txt, contains numbers:
    1
    2
    3
    4
    5
    0
    0
    0
    -2
    -2

    Here's my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
        FILE* spIn;
        FILE* spOut; //for output file
        int   numIn;
    
        spIn = fopen("c:\\aa\\question1.txt", "r");
        if (!spIn)
           {
            printf("Could not open file\a\a\a\n");
            exit  (101);
           } // if open fail 
        
        spOut = fopen("c:\\aa\\outData.txt", "w");
        if (!spOut)
           {
            printf("Could not open file\a\a\a\n");
            exit  (101);
           } // if open fail 
        
        while ((fscanf(spIn, "%d", &numIn)) == 1) {
           fprintf(stdout,"\n%d ", numIn);
           fprintf(spOut,"\n%d ", numIn); //write to output file
        }
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Add some logic to that code to accumulate the count and sum of the input values. All you need is a couple of additional variables (initialised to zero) and then update those variables in the loop.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 06-18-2012, 08:23 AM
  2. Count number of letters and numbers in a file
    By jtullo in forum C Programming
    Replies: 2
    Last Post: 04-21-2008, 01:33 AM
  3. open file with numbers and multiply them
    By autopilot in forum C Programming
    Replies: 30
    Last Post: 09-10-2007, 04:48 PM
  4. Trying to count numbers in file
    By ammochck21 in forum C++ Programming
    Replies: 25
    Last Post: 11-17-2006, 12:32 PM
  5. Read/open file
    By HollyMae in forum C++ Programming
    Replies: 6
    Last Post: 04-10-2003, 03:40 AM