Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to sum up number from a file

Status
Not open for further replies.

ok1397

Technical User
Feb 7, 2005
70
US
Hello everyone, i have a file with numbers and need to add them up to have a total amount. the file looks somewhat like this:

0000063093
0000088847
0000016058
0000003892
0000147681
0000033828
0000068310
0000217651
0000337445
0000002672

In this case the total will be 0000979477. Each time the program runs the numbers will be different & so will the total amount. Is this possible?
 
Yes, this should be doable. First you'll need to open the file as text to read from it easily (should be an example script or three showing how to do this on the samples page of my site). Next, each number that you read is actually a string value when read, so you'll need to use the atoi command to convert to an integer, then add as usual while looping through the file to get the sum.

 
Knob, thank you for responding. I have converted the string to integer but keep getting 0 as a result. here's part of the script.

proc main
string sAmontT
string NAMOUNTFname = "NAMOUNT.TXT"
string NAMOUNTPathname
string sNAMOUNTFile
integer iAmountT
integer iTotalN

fullpath NAMOUNTPathname NAMOUNTFname
sNAMOUNTFile = NAMOUNTPathname

if isfile sNAMOUNTFile
fopen 3 sNAMOUNTFile READ TEXT
else
usermsg "File: NAMOUNT.TXT not found,cannot continue !!!"
pause 1
pwexit
endif

while not feof 3
fgets 3 sAmountT
atoi sAmountT iAmountT
iTotalN = iAmountT + iAmountT
endwhile

strfmt sTotal "Total is %d" iTotalN
usermsg sTotal

fclose 3

endproc
 
proc main
string sAmountT
string NAMOUNTFname = "NAMOUNT.TXT"
string NAMOUNTPathname
string sNAMOUNTFile
integer iAmountT
integer iTotalN

fullpath NAMOUNTPathname NAMOUNTFname
sNAMOUNTFile = NAMOUNTPathname

if isfile sNAMOUNTFile
fopen 3 sNAMOUNTFile READ TEXT
else
usermsg "File: NAMOUNT.TXT not found,cannot continue !!!"
pause 1
pwexit
endif

while not feof 3
fgets 3 sAmountT
atoi sAmountT iAmountT
iTotalN = iAmountT + iAmountT
endwhile

strfmt sTotal "Total is %d" iTotalN
usermsg sTotal

fclose 3

endproc
 
Looks like you have a logic problem here.

You overwrite the value of iAmountT every iteration of your while loop.

Code:
while not feof 3
  fgets 3 sAmountT
    atoi sAmountT iAmountT
    iTotalN = iAmountT + iAmountT    
endwhile

Maybe you meant:

Code:
while not feof 3
  fgets 3 sAmountT
    atoi sAmountT iAmountT
    iTotalN = iTotalN + iAmountT    
endwhile
 
kodr, you are right i didn't realize it. It works perfect now. Thank you for your help!!!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top