Adding numbers in a file

This is a discussion on Adding numbers in a file within the C Programming forums, part of the General Programming Boards category; I need to find the sum of all numbers in a file. I read in the file, but how do ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    13

    Adding numbers in a file

    I need to find the sum of all numbers in a file. I read in the file, but how do i save all the numbers and then add them? Thanks guy/gals.


    Code:
    void sumofnum (int input)
    {
    	FILE* spData;
    	int var;
    
    	spData = fopen ("lab7a.txt", "r");
    
    	if (input == 2)
    	{
    		fscanf (spData, "%d", &var)
    		
    		// Im stuck here
    		
    	}
    	return;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by andone
    I need to find the sum of all numbers in a file. I read in the file, but how do i save all the numbers and then add them?
    Scan them into an array. Then sum the array members.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    13
    is there any other way? Because we haven't learned arrays yet.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Do you actually need to store the numbers? Or merely sum them?

    If you need to store them, what data structures are you allowed to use?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Code:
    sum = 0
    loop(...)
    {
       read number
       sum += number
    }
    print sum
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  6. #6
    Registered User
    Join Date
    Nov 2006
    Posts
    13
    Thanks guys. It lives!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21