3

I'm writing a little program but I have a problem with an if else statement.

@echo off 
set /p points= 
echo %points% 
echo 1x5= 
set /p 15= 
if %15%==5 ( 
    echo well done! 
    set /a points=%points%+1 
) else ( echo wrong! )
pause 
echo %points% 
pause

Even if I fill in a wrong answer, it still ads 1 point to my points and says "Well done!"

(BTW: got some problems with inputting the code, don't now if you will be able to read it)

2 Answers 2

3

When an argument is included in the command line when calling the batch file, it is referenced from code as %1, %2, ... for the first, second, ... parameters.

In your code, when you write if %15%==5 ..., %15% is interpreted as first parameter to batch file (%1) followed by a 5 and a non escaped non paired percent sign that is discarded by the parser. So, if the batch file has no input arguments and %1 is empty, your if code is executed as if 5==5 ...

As a general recomendation, variables in batch files "should" never start with a number, as they will be considered as input arguments.

Sign up to request clarification or add additional context in comments.

Comments

0
@echo off 
setlocal enableDelayedExpansion
set /p points= 
echo %points% 
echo 1x5= 
set /p 15= 
if !15!==5 ( 
    echo well done! 
    set /a points=!points!+1 
) else ( echo wrong! )
pause 
echo !points! 
endlocal
pause

MC MD explained why your code does not work.Here's a way to make it work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.