Reputation: 33
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)
Upvotes: 3
Views: 180
Reputation: 57252
@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.
Upvotes: 0
Reputation: 70923
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.
Upvotes: 3