3

i try to add two numbers received from a file.
But it shows only the last value of sum. Thx for the help!

@FOR /F "eol=; tokens=1-3 delims=, " %%i IN (test.txt) DO (  
   set m=%%j   
   set n=%%k  
   set /a sum=%m%+%n%  
   echo sum = %sum%  
   )  

and in the test.txt i have

alex 4 5  
john 6 7  

and i want to see

sum=9  
sum=13  

it only shows

sum=13  
sum=13
1
  • You failed to note one tiny detail: On first run it will only show sum = . It's not exactl y the last value your loop shows but instead the one from before the loop. Commented Apr 7, 2011 at 14:00

1 Answer 1

2

The problem is the percent expanding in the line set /a sum=%m%+%n% and echo sum = %sum%.
These are expanded before the FOR-loop is executed.

Therefore you got the result of the "global" set of sum.

It's better to use the delayed expansion, as then all variables enclosed with ! are expanded at runtime not parsetime

@echo off
setlocal EnableDelayedExpansion
FOR /F "eol=; tokens=1-3 delims=, " %%i IN (test.txt) DO (  
   set m=%%j   
   set n=%%k  
   set /a sum=m+n
   echo sum = !sum!
)  
Sign up to request clarification or add additional context in comments.

1 Comment

@Alex: Note also that the variables m and n are referenced without using either % or ! around their names on the line that calculates sum. This special way of referencing is allowed in SET /A command and it has the effect of delayed expansion (i.e. it works as if you referenced them like this: set /a sum=!m!+!n!).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.