Thread: Adding numbers in a file

  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,005
    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,005
    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
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    sum = 0
    loop(...)
    {
       read number
       sum += number
    }
    print sum
    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

  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