Thread: Problem with adding up numbers from a txt file

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    1

    Problem with adding up numbers from a txt file

    I'm having a big problem with adding up numbers from a .txt file. I figured out how to count up how many numbers there are in the file, but can't seem to figure out for the life of me how to add up all the numbers in the file for a grand sum. Here is my source code so far:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    
    int main ()
    {
       int high, low, temperature, int average;
       int temperatureCount = 0; 
       char inFileName[PATH_MAX];
       FILE *inFile;
    
       puts("What file to open?");
       gets(inFileName);
       inFile = fopen(inFileName, "r");
    
       if (inFile == NULL) {
          printf("File could not be opened.\n");
          system("pause");
          exit(EXIT_FAILURE);}
       
        while(fscanf(inFile, "%d", &temperature) == 1)                 
              ++temperatureCount;
            
          fclose(inFile);
    
          printf("\n\n%d temperatures read from file.\n\n", temperatureCount);
          average = (temperature/temperatureCount);
          printf("# daily temps : %d,\n", temperatureCount);
          printf("Average temp: %d , \n", average);
          printf("Highest temp: %d, \n", high);
          printf("Lowest temp: %d, \n", low);
    
    system("pause");
    return 0;
    }
    I need to add up all the numbers so that I can get an average temperature. I also need to display the highest temperature and the lowest temperature from the file to the monitor, but have no clue how to do that either. Any help would be appreciated.

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    278
    you need to maintain a running total of the values as you read them in. where you have ++temperatureCount you need to add a sum varuable that adds the latest number.

    You can also add something like if temperature>high then high = temperature. same for the low temperature...

    A funny note, I kept wanting to abbreviate temperature with temp but thought that would be confusing

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Subtle(?) File I/O Problem
    By cecomp64 in forum C Programming
    Replies: 9
    Last Post: 07-16-2008, 11:39 AM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM